Python
Score calculation
Compute correct count and percentage with score.
Answer comparison
To compute the score you compare the user's guess with each question's correct answer. The check_answer method returns whether it is correct using question.answer == guess.
To track the score you add a score attribute to the Quiz class. On each correct answer you write self.score += 1. So when the quiz ends, quiz.score shows how many answers were correct.
The score attribute
You add a score: int = 0 field to the Quiz class. This field starts at zero when the quiz begins; it grows with each correct answer. The int type is for numeric values; the default is 0.
To raise the score you write self.score += 1. This is equivalent to self.score = self.score + 1. When the quiz ends, you can print the score with print(quiz.score). So the app clearly shows the number of correct answers.
Exercise Add check_answer and score
Add a field score: int = 0 to the Quiz class above. Then write the method def check_answer(self, q, guess):; in the body use if q.answer == guess: with self.score += 1 and return True, otherwise return False. After the class create a quiz, add two questions, call quiz.check_answer(quiz.questions[0], "Ankara") and quiz.check_answer(quiz.questions[1], "5"), then print the score with print(quiz.score).
Show example solution
from dataclasses import dataclass, field
@dataclass
class Question:
text: str = ""
answer: str = ""
@dataclass
class Quiz:
questions: list = field(default_factory=list)
score: int = 0
def add_question(self, q):
self.questions.append(q)
def play(self):
for i, q in enumerate(self.questions, start=1):
print(f"Question {i}: {q.text}")
def check_answer(self, q, guess):
if q.answer == guess:
self.score += 1
return True
return False
quiz = Quiz()
quiz.add_question(Question(text="Capital?", answer="Ankara"))
quiz.add_question(Question(text="2x2?", answer="4"))
quiz.check_answer(quiz.questions[0], "Ankara")
quiz.check_answer(quiz.questions[1], "5")
print(quiz.score)
Test yourself
-
What does check_answer return?
- The question text
- The correct answer
- The total score
- True or False
Show answer
True or False — check_answer returns whether the guess is correct as True/False.
-
Complete the score increment line
def check_answer(self, q, guess):
if q.answer == guess:
self.____ += 1
return True
return False
Show answer
def check_answer(self, q, guess):
if q.answer == guess:
self.score += 1
return True
return False
-
Match the scoring parts
- check_answer
- Answer comparison
- score: int = 0
- Initial score
- self.score += 1
- Correct-answer increment
- q.answer == guess
- Equality check
Next lesson: Putting it together