Python — Raising and handling ValueError
In Python, raise ValueError when a token cannot represent a valid seat. A caller can catch that exception and continue checking other inputs.
A simple example
Turn text into a number
- Start with "2"
- Do this Read an integer, add 1
- Result 3
n = int("2")
print(n + 1)
3
Validate a seat number
The parser raises ValueError for malformed text or a seat outside the valid range. Catching that specific exception allows the loop to continue while other programming errors stay visible.
A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
def seat_number(text):
if not text.isascii() or not text.isdecimal():
raise ValueError("expected decimal digits")
number = int(text)
if not 1 <= number <= 8:
raise ValueError("outside seating range")
return number
for text in ["3", "0", "x"]:
try:
print(seat_number(text))
except ValueError:
print("invalid")
3 invalid invalid
Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.
Try it yourself
Predict the results for 8, 9, and an empty string.
Check your answer
Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.