Python conversion and input validation
Convert text safely and handle invalid input.
On this page
Functions, strings, and conditions.
- Convert text safely and handle invalid input.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Text from a form or terminal is not automatically an integer. int converts valid integer text and raises ValueError for invalid numeric syntax.
Catch the specific expected error, then separately check the accepted numeric range. Fixed strings make this sample reproducible without interactive input.
Code example
def parse_age(text):
try:
age = int(text)
except ValueError:
return "Invalid integer"
if age < 0:
return "Age cannot be negative"
return str(age)
print(parse_age("21"))
print(parse_age("abc"))
print(parse_age("-1"))
assert parse_age("0") == "0"21 Invalid integer Age cannot be negative
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
def parse_age(text): try: age = int(text) except ValueError: return "Invalid integer" if age < 0: return "Age cannot be negative" return str(age) print(parse_age("21"))print(parse_age("abc"))print(parse_age("-1"))assert parse_age("0") == "0"Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| For the first call, convert the text 21. | age = 21 | — | |
| Convert the valid result back to display text. | return = 21 | — | |
| Print the successful result. | return = 21 | 21 | |
| The abc call raises ValueError at int and enters this handler. | return = 21 | 21 | |
| Print the conversion error message. | return = 21 | 21 Invalid integer | |
| The -1 call converts successfully but fails range validation. | age = -1 | 21 Invalid integer | |
| Print the range error. | age = -1 | 21 Invalid integer Age cannot be negative | |
| Check that zero is accepted. | age = -1 | 21 Invalid integer Age cannot be negative |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
Cost and common mistakes
O(n) parsing work for bounded integer text of length n; the converted value also occupies memory.
- Catching every exception can hide unrelated bugs.
- The function expects a string; it is not a general validator for arbitrary objects.
Try it yourself
Add an upper bound of 130.
Reveal answer and reasoning
Reject age > 130 with a separate message. Test 130 as accepted and 131 as rejected.