Sub topic 5
Handling bad input with try/except and retry loops
This chapter assumes you can write while loops and basic try/except blocks, and that you know input() always returns a str. The previous chapter showed that int() converts text to a number. Here you will handle the case where that conversion fails, and you will turn the handling into a reusable function.
What can go wrong when you read input
A user can type anything, so a program that reads input must expect values it cannot use. Three kinds of failure matter in practice.
| Situation | What Python does | Typical response |
|---|---|---|
| Text that is not a valid number, such as `abc` or `3.5` passed to `int()` | `int()` raises `ValueError` | Explain the problem and ask again |
| Number that parses but is out of range, such as `-4` for an age | Nothing is raised, so your code must check | Explain the limit and ask again |
| Input stream ends (Ctrl+D on Linux and macOS, Ctrl+Z then Enter on Windows, or a closed pipe) | `input()` raises `EOFError` | Stop, or fall back to a default |
| User presses Ctrl+C | `KeyboardInterrupt` is raised | Let it end the program |
The first two are ordinary mistakes you should retry. The last two mean the user or the environment wants to stop, so a retry loop should not swallow them.
The basic retry loop
A retry loop repeats an attempt until it succeeds. The structure is while True, then try around the one risky call, then else for the success path.
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}.")Each part has a job:
input()sits outside thetry. It is not the line that raisesValueError, so there is no reason to guard it.- Only
int(raw)sits inside thetry. A narrowtrymeans that aValueErrorfrom some other line cannot be mistaken for bad input. except ValueErrorruns when conversion fails. It prints a message and falls off the end of the block. Control returns to the top of thewhile, so the loop retries.elseruns only when thetrybody raised nothing.breakthere leaves the loop.{raw!r}usesrepr(), so an empty entry shows as''instead of a blank gap, and trailing spaces become visible.
What int() accepts and rejects
Knowing the parser's rules lets you predict which inputs reach your except block.
samples = ["42", " 42 ", "1_000", "+7", "3.5", "", "4 2", "0x1F", "٣"]
for s in samples:
try:
print(f"{s!r:>9} -> {int(s)}")
except ValueError:
print(f"{s!r:>9} -> ValueError")Running it shows these results:
"42"," 42 ","1_000"(1000),"+7"and"٣"(the Arabic-Indic digit three, which becomes 3) are all accepted."3.5","","4 2"and"0x1F"raiseValueError. A hex literal needsint(s, 16).
Surrounding whitespace is ignored, so you do not need strip() just for int(). You do need it if you compare the raw text yourself, for example when checking for an empty answer.
float() is more permissive than most people expect. It accepts "nan", "inf" and "1e3".
print(float("nan"), float("inf"), float("1e3"))
print(0 <= float("nan") <= 100)The last line prints False, because every comparison with nan is false. A range check written as low <= value <= high therefore rejects nan, but inf fails it only when high is finite. If you accept floats, check the range with that chained form instead of checking for the bad cases (value < low or value > high), which lets nan through.
A reusable validating function
Copying a retry loop into every prompt invites small differences. Put it in a function that takes the prompt and the limits, and let it handle both parse errors and range errors.
class TooManyAttempts(Exception):
"""Raised when the user fails to give valid input in time."""
def ask_int(prompt, low=None, high=None, max_tries=None):
tries = 0
while True:
raw = input(prompt)
try:
value = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number.")
else:
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
tries += 1
if max_tries is not None and tries >= max_tries:
raise TooManyAttempts(f"no valid input after {tries} tries")
if __name__ == "__main__":
try:
age = ask_int("Age (0-130): ", low=0, high=130, max_tries=3)
except TooManyAttempts as exc:
print(f"Giving up: {exc}")
except EOFError:
print("\nInput ended before an answer was given.")
else:
print(f"Next year you will be {age + 1}.")Design points worth noticing:
return valuereplacesbreak. A function exits the loop and hands back the result in one step.- The range check is in the
elsebranch, after a successful conversion. It is ordinaryif/eliflogic, not an exception, because an out-of-range number is not a parse error. max_triesis optional. Interactive programs usually loop forever. Scripts that might run unattended, or tests, need a limit so they cannot hang.- A custom exception,
TooManyAttempts, gives the caller a precise signal. RaisingValueErrorinstead would make "gave up" look the same as "typed letters". - The
EOFErrorhandler lives in the caller. The caller knows whether stopping means exiting the program, using a default, or aborting one task.
Choosing which exceptions to catch
The most common mistakes in retry loops come from catching too much.
- Bare
except:. It also catchesKeyboardInterrupt, so Ctrl+C no longer stops the program, and it hides typos such as a misspelled variable name (NameError). except Exception:. It does not catchKeyboardInterrupt, but it does catchEOFError. When stdin is closed,input()fails immediately on every call, and the loop prints its error message forever.- A
trythat wraps many lines. If the body also does arithmetic or looks up a key, aValueErrorfrom that code is reported to the user as bad input. Keep only the conversion in thetry.
Testing a retry loop without typing
You can test a loop by feeding it input from a pipe. Save the ask_int program as age.py and run this in a Unix shell:
import subprocess
import sys
result = subprocess.run(
[sys.executable, "age.py"],
input="abc\n-5\n200\n42\n",
capture_output=True,
text=True,
)
print(result.stdout)The first three lines are rejected, each with its own message, and 42 is accepted. Because the text contains four lines, the program never reaches the end of its input. If you supply only abc\n, the program hits EOFError on the second prompt and prints the end-of-input message from the caller.
Other validation styles
Exceptions are the natural fit for numbers because int() already does the checking. Other fields use different tools.
- Method checks.
raw.isdigit()is true for some characters thatint()rejects, such as superscript digits like"²". It is also false for"-5". Prefertry/exceptfor numbers. - Membership checks. For a menu, compare against a set:
choice = raw.strip().lower(), thenif choice in {"y", "n"}. - Default on empty. Treat
raw.strip() == ""as "use the default" before attempting conversion.
This pattern is called EAFP, short for "easier to ask forgiveness than permission". You attempt the operation and handle failure. The alternative, LBYL ("look before you leap"), tests first. EAFP works well for numbers because the parser has rules that are tedious to reproduce, such as signs, underscores and Unicode digits.
Exercise
A learner writes while True: with try: n = int(input("N: ")) and except: print("bad"), and finds that Ctrl+C no longer stops the program. What is the cause, and what is the minimal fix?
Show answer
A bare except: catches every exception, including KeyboardInterrupt, so Ctrl+C is treated as bad input and the loop continues. Change it to except ValueError:. That catches only failed conversions and lets Ctrl+C end the program.
Exercise
Write ask_float(prompt, low, high) that keeps asking until the user enters a float with low <= value <= high. It must reject nan, and it must not loop forever if standard input is closed.
Show answer
def ask_float(prompt, low, high):
while True:
raw = input(prompt)
try:
value = float(raw)
except ValueError:
print(f"{raw!r} is not a number.")
continue
if low <= value <= high:
return value
print(f"Enter a number from {low} to {high}.")
The chained comparison is false for nan, so nan is rejected. EOFError is not caught, so a closed stdin ends the program with a traceback instead of looping. A caller that wants a friendlier message can catch EOFError around the call.