Validate the Range
Add a range check so answers outside 1-4 re-prompt instead of being accepted
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The retry loop now handles non-numbers — but int("5") succeeds, so the player can answer 5, 99, or -1 without any complaint. Those are not valid choices.
After parsing the integer, check whether it falls in the valid range:
while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
except ValueError:
print("Please enter 1, 2, 3, or 4.")
continue
if answer < 1 or answer > 4:
print("Please enter 1, 2, 3, or 4.")
continue
breakcontinue restarts the loop
continue skips the rest of the loop body and jumps back to the top. Both the except block and the range check use continue to restart the prompt. Only a valid integer between 1 and 4 reaches break.
Why break moves out of try
In the previous chapter, break sat inside try. That worked because any valid integer was also a valid choice. Now that range validation lives *after* try, break must move there too — otherwise the loop could exit before the range check runs.
Instructions
Add a range check and move break to after the validation.
- Remove
breakfrom inside thetryblock — it needs to move to after the range check so the loop can only exit when the input is both a valid integer and within 1–4. - In the
except ValueErrorblock, addcontinueafterprint("Please enter 1, 2, 3, or 4.")—continueskips the rest of the loop body and restarts the prompt immediately, without reaching the range check. - After the
try/exceptblock (still insidewhile True:), addif answer < 1 or answer > 4:, thenprint("Please enter 1, 2, 3, or 4.")andcontinue— this catches valid integers outside the allowed range, like5or-1, and re-prompts. - After the
ifblock (still insidewhile True:), addbreak— only a valid integer between 1 and 4 reaches this line, so the loop exits and the quiz proceeds.
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()
while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
break # Step 1: Move this break — remove it from here
except ValueError:
print("Please enter 1, 2, 3, or 4.")
# Step 2: Add continue here
# Step 3: if answer < 1 or answer > 4: print message, continue
# Step 4: break
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