Intermediate 12 min

Errors and input validation

Handle a predictable bad input and trace unexpected Python errors.

Follow the traceback

An exception interrupts the normal flow. Start near the end of the traceback to identify its type and message, then find the most relevant line in your own code. A small reproducible input makes the problem easier to inspect.

How it works

Ask which step can fail and how the program should respond. Numeric parsing can fail because the text is malformed; a limit check can fail even after parsing succeeds. Keep the guarded operation small, so a recovery action handles only the error you expected.

Handle the conversion narrowly

Wrap int(text) in a short try block and catch ValueError when that value cannot be interpreted as an integer. Keep unrelated operations outside that block so their failures remain visible. After conversion, check the allowed range separately.

Code example

def parse_seats(text):
    try:
        seats = int(text)
    except ValueError:
        return "Enter a whole number"
    if seats < 1:
        return "Enter at least one seat"
    return seats

print(parse_seats("2.5"))

Check your understanding

Predict what parse_seats returns for each string.

See the example and explanation
Example 1
Given "2.5"
Answer Enter a whole number
Example 2
Given "0"
Answer Enter at least one seat
Example 3
Given "8"
Answer 8

The decimal string hits the exception handler. Zero converts successfully and fails the range check. The string "8" converts and returns the integer 8.

Open practice problem
Next lessonList and dictionary comprehensions