Validate the Range
Exit

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
    break

continue 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.

  1. Remove break from inside the try block — 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.
  2. In the except ValueError block, add continue after print("Please enter 1, 2, 3, or 4.")continue skips the rest of the loop body and restarts the prompt immediately, without reaching the range check.
  3. After the try/except block (still inside while True:), add if answer < 1 or answer > 4:, then print("Please enter 1, 2, 3, or 4.") and continue — this catches valid integers outside the allowed range, like 5 or -1, and re-prompts.
  4. After the if block (still inside while True:), add break — only a valid integer between 1 and 4 reaches this line, so the loop exits and the quiz proceeds.