Track the Score
Add score and total variables to count how many questions the player got right
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The quiz tells the player whether each answer is right or wrong, but it doesn't say how they did overall. With three questions in play, a running score is now meaningful.
Score variables
Add score and total before the loop:
score = 0
total = 3score starts at zero and increments each time the player answers correctly. total is the number of questions.
Updating the score
Inside the if is_correct: block, add one to score before printing the feedback:
if is_correct:
score = score + 1
print("Correct!")score = score + 1 reads the current value of score, adds one, and stores the result back.
Displaying the score
After the for loop, print the final score:
print(f"Score: {score}/{total}")This runs once after all three questions are done and shows something like Score: 2/3.
Instructions
Add score tracking to quiz.py.
- Before
print("=== Python Quiz ==="), create a variable namedscoreand assign it0. - After
score = 0, create a variable namedtotaland assign it3. - Inside the
if is_correct:block, beforeprint("Correct!"), addscore = score + 1. - After the
forloop, callprint(f"Score: {score}/{total}").
QUESTIONS = [
("What is the type of the value 3.14?", "int", "str", "float", "bool", 3),
("What keyword defines a function in Python?", "for", "def", "if", "class", 2),
("What does print() do?", "Stores a value", "Returns a number", "Displays output", "Reads input", 3),
]
# Step 1: Create score variable set to 0
# Step 2: Create total variable set to 3
print("=== Python Quiz ===")
print()
for text, o1, o2, o3, o4, correct in QUESTIONS:
print(text)
print()
print(f" 1) {o1}")
print(f" 2) {o2}")
print(f" 3) {o3}")
print(f" 4) {o4}")
print()
answer_text = input("Your answer (1-4): ")
answer = int(answer_text)
is_correct = answer == correct
print()
print(f"You answered: {answer}")
if is_correct:
# Step 3: Add 1 to score using score = score + 1
print("Correct!")
else:
print(f"Wrong! The correct answer was option {correct}.")
# Step 4: Print score as "Score: {score}/{total}"
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding