Keep Asking
Replace return False with a retry loop so invalid input re-prompts instead of counting as wrong
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Counting a typo as a wrong answer is frustrating. A better approach: re-prompt the player until they enter a valid number.
The while True + break pattern handles this:
while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
break
except ValueError:
print("Please enter 1, 2, 3, or 4.")- The loop runs forever — until
breakexits it. - If
int()succeeds,breakexits the loop and the question continues. - If
int()raises aValueError, theexceptblock prints the message. The loop then restarts automatically, asking the player again.
Why break is inside try
break only runs if int() succeeds. If int() raises an exception, Python jumps to except — skipping break. The loop restarts and prompts the player again.
Without break, the loop would run forever even after a valid answer. Without try/except, a bad answer would still crash the quiz.
Instructions
Upgrade ask_question to retry on invalid input instead of counting a typo as a wrong answer.
- Add
while True:beforeanswer_text = input(...)and re-indentanswer_text = input(...)and thetry/exceptblock inside it — the loop keeps re-prompting the player until they enter a valid number. - Inside the
tryblock, addbreakon the line afteranswer = int(answer_text)—breakonly runs ifint()succeeds, so a valid answer exits the loop immediately. - Remove
return Falsefrom theexcept ValueErrorblock — the loop now handles invalid input by restarting the prompt, so there is no longer a reason to return early.
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),
]
def ask_question(text, o1, o2, o3, o4, correct):
print(text)
print()
print(f" 1) {o1}")
print(f" 2) {o2}")
print(f" 3) {o3}")
print(f" 4) {o4}")
print()
# Step 1: while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
# Step 2: break
except ValueError:
print("Please enter 1, 2, 3, or 4.")
return False # Step 3: Remove this line
is_correct = answer == correct
print()
print(f"You answered: {answer}")
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {correct}.")
return is_correct
def show_results(score, total):
print(f"Score: {score}/{total}")
if score == total:
print("Perfect score!")
elif score >= 2:
print("Great job!")
elif score >= 1:
print("Not bad!")
else:
print("Keep practicing!")
def run_quiz(questions=QUESTIONS):
total = len(questions)
score = 0
streak = 0
print("=== Python Quiz ===")
print()
for text, o1, o2, o3, o4, correct in questions:
result = ask_question(text, o1, o2, o3, o4, correct)
if result:
score = score + 1
streak = streak + 1
if streak >= 3:
print(f" Hot streak! ({streak} in a row)")
else:
streak = 0
show_results(score, total)
while True:
run_quiz()
print()
again = input("Play again? (y/n): ")
if again != "y":
break
print("Thanks for playing!")
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding