Catch Invalid Input
Exit

Catch Invalid Input

Wrap int() in a try/except block so bad input prints a message instead of crashing

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Right now, ask_question calls int(answer_text) with no protection. If the player types abc, the ValueError crashes the quiz.

A try/except block catches the error and runs alternative code instead:

try:
    answer = int(answer_text)
except ValueError:
    print("Please enter 1, 2, 3, or 4.")
    return False

Python runs the try block. If int() succeeds, the quiz continues normally. If int() raises a ValueError, Python skips the rest of try and runs the except block — printing a message and returning False so the question counts as wrong.

How try/except works

  1. Python runs the code inside try.
  2. If no error occurs, Python skips except entirely.
  3. If a ValueError occurs, Python stops the try block and runs except.

Returning False on bad input is a simple first fix. The player cannot crash the quiz, but a typo counts as a wrong answer. You will improve this in the next chapter.

Instructions

Replace the plain int() call in ask_question with a try/except block.

  1. Replace answer = int(answer_text) with a try block containing answer = int(answer_text) — wrapping it in try means Python will attempt the conversion but hand control to except if it fails, instead of crashing.
  2. Add an except ValueError block. Inside, call print("Please enter 1, 2, 3, or 4.") and then return FalseValueError is the specific error int() raises for non-numeric input; return False treats the bad input as a wrong answer so the quiz can continue without crashing.