──────────────────────────────────────

34. The Repair Bench · Recover from Bad Input

Handle a failed conversion and distinguish it from an out-of-range number.

Lesson files · lessons/debugging-and-tests/handle-value-error

Before you start
- Read a whole number with int(input()).
- Use a comparison to check a number against two limits.
- Read an error type from the last line of a traceback.

By the end
- Use try and except ValueError to handle a failed conversion.
- Use the else branch to check a number that converted successfully.
- Test a word, an allowed age and an age outside the range.

Where you can use it
Ask a player how many rounds to play. Give a helpful response when they type a word or enter a number outside the allowed range.

Put int(input()) in the try block. If the conversion fails, the except ValueError block runs. Put the conversion on its own in try so you can see exactly which step the handler covers.

The else aligned with try runs when the conversion succeeds. Inside that block, use if to check the number's range. For example, twelve fails conversion, while -1 converts and fails the range check.

Predict
Which branch receives the input three?
- else
- except ValueError

Worked example (example.py)

try:
    count = int(input())
except ValueError:
    print("Use a number.")
else:
    print(f"Count: {count}")


Example input
three

Example result
Use a number.

Read an age. If the reply cannot be converted to a whole number, print Use a number. If the number is below 0 or above 120, print Use 0 to 120. For a number in that range, print Age: followed by the age.

Starter program (starter.py)

try:
    count = int(input())
except ValueError:
    print("Use a number.")
else:
    print(f"Count: {count}")


Starter input
three

Hint
Use a narrow try/except around conversion. In else, test 0 <= age <= 120.

Case 1. Try the sample
Input
12
Expected output
Age: 12

Case 2. Non-number
Input
twelve
Expected output
Use a number.

Case 3. Outside the range
Input
-1
Expected output
Use 0 to 120.

Stretch
Try 120 and 121 to check the upper limit. Then try accepting up to two attempts before printing a final message.

Reflect
Why does -1 need a different response from twelve?

Check your prediction
except ValueError int cannot convert the word three into an integer.
