g↗genai/ learner
Python for AI / Lesson 11

Errors and safe parsing

Turn text into a number, handle a conversion error, and check whether the number fits your task.

Concept + interactive labBeginner friendly

From text to a usable number

Imagine a form asking how many documents to process. This example accepts whole numbers from 0 to 5, including both ends.

  1. Parsing: turn text into a value, such as the integer 3.
  2. Exception: a signal that an operation could not finish normally. We will handle a ValueError from conversion.
  3. Validation: check whether a converted value meets the form’s rule.

These are separate steps: a number can parse successfully and still be outside the allowed range.

Parse the text first

A written label is not the object it describes. Similarly, '3' is text; 3 is an integer, a whole-number value.

Text 3 goes through int and becomes number 3.
The text 3 becomes the number 3.
text = '3'
number = int(text)  # number is 3

int converts this text to an integer. For example, a quantity typed into a shopping form also starts as text and may need conversion before arithmetic.

Python accepts leading or trailing whitespace and an optional sign attached to the digits: int(' -1 ') returns -1. It does not accept every string; int('three') raises ValueError.

Handle a conversion error

Like a clerk setting aside an unreadable form, an exception handler gives the program a path for an expected problem. An exception interrupts the normal path; an unhandled one can stop the program.

The text three enters int, which raises ValueError.
This conversion raises ValueError.
text = 'three'
try:
    number = int(text)
except ValueError:
    print('Enter a whole number.')
else:
    print('Converted:', number)

Python tries the conversion. For 'three', it jumps to the matching except and skips else; no number was assigned by that conversion. For '3', conversion succeeds and else runs.

Keep the try block narrow so the handler identifies this expected failure. Other exceptions are not handled by this except ValueError.

For another example, a program reading an age can ask for a new entry when conversion fails instead of pretending the age was zero.

Validate the converted value

Parsing asks “is this a number?” Validation asks “is this number allowed here?” A successfully read ticket number can still be outside the event’s valid range.

The number 7 is checked against 0–5 and rejected.
The range rule rejects 7.
text = input('Documents (0–5): ')
try:
    number = int(text)
except ValueError:
    print('Enter a whole number.')
else:
    if 0 <= number <= 5:
        print('Accepted:', number)
    else:
        print('Choose from 0 to 5.')

For '7', conversion returns 7; the range check rejects it. For '0', conversion returns 0 and the rule accepts it. Do not use zero as an error substitute: it is a valid answer here.

The check sits in else, so a failed conversion never attempts to use number. This one attempt reports the problem; a caller or user can try again.

Quick questions

  • Does an exception prove the user entered zero? No, the conversion did not produce a number.
  • Does successful conversion prove the value is allowed? No, the range rule is separate.

Trace the two steps

With '3', conversion produces 3 and the range check accepts it. Now compare other examples.

  1. Select a sample text.
  2. Read the conversion result.
  3. Check whether validation runs and compare the outcome.

This illustration uses fixed examples to expose each path; it is not a running Python interpreter or a complete parser.

Conversion: int('3') returns 3.

Next: 3 is within 0–5: accept it.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

A form accepts whole numbers from 0 to 5 inclusive. The text '7' is passed to int(). What happens in the example above?

Take this with you

Convert text, handle the expected conversion error, then validate the value against the task’s rule. Keep valid values such as zero distinct from failure.

Return to Python for AI