Sub topic 5
Handling bad input with try/except and retry loops
This chapter assumes you know while loops, try and except, and that input() returns a string. Users type unexpected things, and int() raises ValueError when it can't convert the text. Here you will catch that error and ask again instead of crashing.
The basic retry loop
The pattern has three parts: loop forever, try the conversion, and leave the loop only when it works.
while True:
raw = input("Age: ")
try:
age = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number, try again.")
else:
break
print(f"Next year you will be {age + 1}.")The else block runs only when the try block raised no exception. Putting break there keeps the try block small. The !r conversion shows the text with quotes, so an empty answer prints as '' and is easy to notice.
What fails and what passes
int() is stricter than you might expect in some ways and looser in others.
| Input | `int(raw)` result |
|---|---|
| `"42"` | `42` |
| `" 42 "` | `42`, surrounding whitespace is ignored |
| `"4.5"` | `ValueError` |
| `""` | `ValueError` |
| `"1_000"` | `1000`, underscores are allowed |
Catch ValueError specifically. A bare except: would also swallow KeyboardInterrupt, so the user could no longer stop the program with Ctrl+C.
A reusable function with range checks
A conversion can succeed and still give a value your program can't use, such as an age of -5. Wrap the loop in a function so the rules live in one place.
def ask_int(prompt, low=None, high=None):
while True:
raw = input(prompt)
try:
value = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number, try again.")
continue
if low is not None and value < low:
print(f"Enter a number that is at least {low}.")
elif high is not None and value > high:
print(f"Enter a number that is at most {high}.")
else:
return value
age = ask_int("Age: ", low=0, high=130)
print(f"Next year you will be {age + 1}.")Here continue restarts the loop after a conversion error. A return inside the loop ends both the loop and the function, so no break is needed.
Input that ends
When standard input closes, input() raises EOFError. This happens when the user presses Ctrl+D (Ctrl+Z then Enter on Windows) or when a pipe runs out of data. A loop that only catches ValueError will crash with a traceback here. If your program must stop cleanly, catch it outside the loop.
import sys
try:
age = ask_int("Age: ", low=0, high=130)
except EOFError:
print("No input received.", file=sys.stderr)
sys.exit(1)This code reuses ask_int from the previous example. The message goes to standard error, so it stays out of any output the user redirects to a file.
Common mistakes
- Putting the
input()call outside the loop. The loop then retries the same bad string forever. - Wrapping a large block in
try. AnyValueErrorfrom unrelated code is then reported as bad input. - Printing a vague message such as "Invalid." Say what was expected and show what was received.
- Using a retry loop on piped or automated input. Bad data never changes, so the loop can run forever. For scripts that read from pipes, fail with a message instead.
Exercise
Write a function ask_float(prompt) that keeps asking until the user enters a finite number, and returns it as a float. Which exception do you catch, and which extra check do you need after the conversion?
Show answer
Catch ValueError around float(raw). After a successful conversion, check math.isfinite(value) and ask again if it is false, because float() accepts "nan" and "inf". Example: import math def ask_float(prompt): while True: raw = input(prompt) try: value = float(raw) except ValueError: print(f"{raw!r} is not a number, try again.") continue if math.isfinite(value): return value print("Enter a finite number.")