Validate input and retry safely
Raise errors at a function boundary, then recover in the caller.
Jump to the automation labUse raise ValueError(...) when conversion succeeds but the value is outside your program’s allowed range. The caller can handle bad input without duplicating the validation rules.
Put only the conversion and validation inside try. Use else for work that should run on success, and finally for cleanup that must run regardless of the outcome. A bare pass in an exception handler silently discards the error. Use it only when discarding that specific error is intentional.
A retry loop should have an exit for a valid value and a way out when the input ends. A real terminal also raises KeyboardInterrupt when the user presses Ctrl+C.
Conversion raises ValueError.
Worked examples
Run cleanup even when conversion fails
The finally block prints the completion message in both runs. In file-handling code, with usually takes care of cleanup.
def show_count(text):
try:
count = int(text)
except ValueError:
print("Invalid count")
else:
print(f"Count: {count}")
finally:
print("Attempt finished")
show_count("8")
show_count("eight")Run the example and practice
Allow bookings of one to six seats. Add a range check to parse_seats and raise ValueError on an out-of-range number. Let read_seats handle both kinds of invalid input.
Target output
Try again.
Try again.
Seats: 5Show a hint
Assign int(text) to a local variable. Use a chained comparison before returning it.
Run code uses the input here. Check output uses the original sample input.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
def parse_seats(text):
seats = int(text)
if not 1 <= seats <= 6:
raise ValueError("Bookings allow one to six seats.")
return seats
def read_seats():
while True:
try:
seats = parse_seats(input())
except ValueError:
print("Try again.")
except EOFError:
return None
else:
return seats
print(f"Seats: {read_seats()}")Automation lab
Ask for a valid carton size
A packing list needs a size from 1 to 24. Reuse one validation function for each attempt.
Ready
Run the example to see the output here.
Enter 0 followed by 24 on the next line to check two boundary cases.
Further reading in Automate the Boring Stuff with Python by Al Sweigart