Handle Wrong Answers
Add an else branch to print feedback when the player's answer is wrong
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
When the player answers correctly, the quiz prints "Correct!" But when they are wrong, nothing happens — the program ends silently. You need to handle that case.
The else clause
An else clause runs when the if condition is False. Together, if and else cover every possible outcome:
if condition:
# runs when True
else:
# runs when FalseExactly one branch runs — never both, never neither.
Applying it to PyQuiz
When is_correct is False, tell the player which option was correct:
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {correct}.")correct holds the number of the right option. For example, if correct is 3, the player should have chosen option 3.
Instructions
Add a wrong-answer message to the existing if statement.
- After
print("Correct!"), add anelseclause that callsprint(f"Wrong! The correct answer was option {correct}.")— theelseblock runs whenis_correctisFalse, so every answer now gets a response: correct answers see "Correct!", wrong answers see the right option number.
question = "What is the type of the value 3.14?"
option_1 = "int"
option_2 = "str"
option_3 = "float"
option_4 = "bool"
correct = 3
print("=== Python Quiz ===")
print()
print(question)
print()
print(f" 1) {option_1}")
print(f" 2) {option_2}")
print(f" 3) {option_3}")
print(f" 4) {option_4}")
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:
print("Correct!")
# Step 1: Add an else clause that prints "Wrong! The correct answer was option {correct}."
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding