Python · Course navigation

Python conversion and input validation

Convert text safely and handle invalid input.

On this page
Before you start

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

Python
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"
Output
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
Guided walkthroughReady
1def parse_age(text):
2 try:
3 age = int(text)
4 except ValueError:
5 return "Invalid integer"
6 if age < 0:
7 return "Age cannot be negative"
8 return str(age)
9
10print(parse_age("21"))
11print(parse_age("abc"))
12print(parse_age("-1"))
13assert 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading