1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

try / except

Some errors are expected, such as bad user input or dividing by zero. try lets you catch them instead of crashing:

try:
    n = int(text)
except ValueError:
    n = 0

Catch the specific error you expect, not everything.

A try can also have else and finally blocks, and as e gives you the error object:

try:
    n = int(text)
except ValueError as e:    # e holds the error; str(e) is its message
    print("Bad input:", e)
else:                      # runs only when no error happened
    print("Got", n)
finally:                   # always runs last, error or not
    print("Done")

See it run

def read(text):
    try:
        n = int(text)
    except ValueError:
        n = 0
    else:
        print("parsed", n)
    finally:
        print("done")
    return n

read("12")
read("hi")

Watch which lines light up on each call: some are skipped.

Practice try / except

Exercise 1

  • safe_divide(a, b) returns a / b, or None if b is 0 (catch ZeroDivisionError).
  • to_int(text) returns int(text), or 0 if the text cannot be converted to an integer, such as "hi" or "3.5" (catch ValueError).

Exercise 2

Write parse_age(text): return an integer age from 0 through 120 inclusive. Return None for non-integer text or an integer outside that range. Catch ValueError for bad numeric text; do not turn a valid zero into a missing age.

Exercise 3

Write readings_average(texts). Try converting each string with float; skip ValueError entries. Return the mean of valid readings, including zero and negative readings, or None when none are valid. All supplied numeric readings are finite.

Exercise 4

Write parse_qty(text) that returns a list of log messages:

  • try int(text); catch ValueError as e and add "error: " followed by str(e)
  • in an else block, add "ok: N" with the number
  • in a finally block, always add "checked" last

So parse_qty("4") returns ["ok: 4", "checked"] and parse_qty("x") returns ["error: invalid literal for int() with base 10: 'x'", "checked"].

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest