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 break exits it.
  • If int() succeeds, break exits the loop and the question continues.
  • If int() raises a ValueError, the except block 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.

  1. Add while True: before answer_text = input(...) and re-indent answer_text = input(...) and the try/except block inside it — the loop keeps re-prompting the player until they enter a valid number.
  2. Inside the try block, add break on the line after answer = int(answer_text)break only runs if int() succeeds, so a valid answer exits the loop immediately.
  3. Remove return False from the except ValueError block — the loop now handles invalid input by restarting the prompt, so there is no longer a reason to return early.