Junior Codes
The Sky Expedition · stretch

Python try and except for Kids: Handling Errors

Catch errors so your program copes instead of crashing.

Start Wonderwild free with Pip

Try 5 starter activities free. Full access is ₹499 a year.

This mission is part of full access. The first missions are free to try.

try / except, explained simply

If someone types "seven" when your program expects 7, int() raises an error and the program stops. Real programs need to cope with mistakes like that.

Put the risky line inside a try block. If it works, great. If a particular error happens, Python jumps to the matching except block instead of crashing.

Name the error you expect, such as ValueError, so you only catch the problems you know how to handle. Combine try with a while loop to keep asking until the answer makes sense.

Example: An unbreakable question

while True:
    answer = input("How many tickets? ")
    try:
        tickets = int(answer)
        break
    except ValueError:
        print("Please type a number, like 2.")
print(f"Booking {tickets} tickets.")

Output

How many tickets? two
Please type a number, like 2.
How many tickets? 2
Booking 2 tickets.

Try this

  • Also reject numbers below 1 with an if check inside the loop.
  • Catch ZeroDivisionError in a program that divides two numbers.
  • Remove the except block and see what the error looks like.

Practise it in Wonderwild

“The unbreakable ticket booth”

Mission 31 in The Sky Expedition, one of 36 Python missions in Wonderwild.

Your child writes and runs real Python in the browser while Pip reacts to every line. Nothing to install. For ages 7+.

Start Wonderwild free with Pip

Try 5 starter activities free. Full access is ₹499 a year.

This mission is part of full access. The first missions are free to try.

Questions parents and kids ask

Should I catch every error with a plain except?+

It is better to name the error you expect. A plain except can hide real bugs you would want to know about.

Why is this a stretch topic?+

It combines loops, input, type conversion and decisions. It is easiest once those feel comfortable, which is why Wonderwild places it in the optional stretch chapter.

Prefer learning with a teacher?

Our live Python for Young Developers course teaches these ideas in small online classes led by a software engineer, with projects and feedback. Every live course also includes 12 months of full Wonderwild access for practice.

See the Python for Young Developers course