Lesson 14 of 30

Lesson 14 ? Friendly errors

Title: Read errors without fear

Description: Learn common Python errors and use try / except for simple input mistakes.

Why it matters for kids: Errors are clues. They help you fix your program.


1. A name error

pythonpython
name = "Ava"
print(name)

If you wrote print(nam), Python would complain because nam does not exist.


2. A type error

pythonpython
age = 9

print("Age:", age)
print("Next age:", age + 1)

This works because age is a number. Text and numbers need careful handling.


3. Convert input safely

pythonpython
age_text = input("Age: ")
age = int(age_text)

print("Next year:", age + 1)

This works when the user types a number.


4. Try again message

pythonpython
try:
    age = int(input("Age: "))
    print("Next year:", age + 1)
except ValueError:
    print("Please type a whole number.")

5. Easy examples

pythonpython
try:
    cookies = int(input("Cookies: "))
    print("Double cookies:", cookies * 2)
except ValueError:
    print("Numbers only, please.")
pythonpython
try:
    answer = 10 / 2
    print(answer)
except ZeroDivisionError:
    print("Cannot divide by zero.")
pythonpython
items = ["pencil", "book"]

try:
    print(items[5])
except IndexError:
    print("That item is not in the list.")

6. Mini challenge

Click each example to open it.

Example 1

Fix one misspelled variable name.

Example 2

Convert age text to a number.

Example 3

Catch ValueError for age input.

Example 4

Catch ValueError for cookie input.

Example 5

Try dividing 10 by 2.

Example 6

Catch divide by zero.

Example 7

Create a list with two items.

Example 8

Catch a wrong list index.

Example 9

Print a friendly error message.

Example 10

Ask for stickers and handle text input.