computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🔍

🎓

⏱ 25 min

Free

Debugging Like a Pro

Read error messages, find bugs fast and handle problems with try/except.

🎯 What you will learn

  • Read Python error messages
  • Use print() to investigate bugs
  • Handle errors with try/except

👋 Let’s get started!

Error messages aren’t scary — they’re clues! 🕵️ Pro coders spend lots of time debugging. Learn their tricks and you’ll fix bugs in seconds.

🪜 Step by step

1. 📜 Read the error

The last line tells you the error type and message. The line number tells you where.

print("Hello)
# SyntaxError: unterminated string literal
2. 🔦 Print debugging

Add print() lines to see what your variables really contain.

total = 0
for n in [1, 2, 3]:
    total = total + n
    print("n =", n, "total =", total)
3. 🛡️ try / except

Catch errors so your program doesn’t crash.

try:
    age = int("twelve")
except ValueError:
    print("Please type a number like 12")

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Safe divider

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Can't divide by zero! 🙅"

print(safe_divide(10, 2))
print(safe_divide(5, 0))

Catch a bad answer

answer = "seven"
try:
    number = int(answer)
except ValueError:
    print("That is not a number!")

📖 Key words

Tap a card to flip it over!

Error message
Python’s clue about what went wrong 📜
Traceback
The trail showing where the error happened 👣
try/except
Catches errors so the program keeps going 🛡️

🏆 Challenge

This code has 2 bugs. Fix them so it prints: Total: 15

Challenge

numbers = [5, 5, 5]
total = 0
for n in numbers
    total = total + n
print("Total: " + total)

Knowledge Check Quiz

  1. Which error happens here?
  2. What does except do?
  3. Best first step when you see an error?
← Previous lesson
Next lesson →