Python · Errors and Exceptions
Understanding errors
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What Are Errors in Python?
When you write Python code, you'll encounter errors. Don't worry - errors are not bad! They're actually Python's way of helping you understand what went wrong.
Think of errors like a Codémon trainer giving you feedback: "Hey, you can't make a Codémon fly without wings!" Similarly, Python tells you: "Hey, you can't divide by zero - that doesn't make sense!" or "Hey, I don't know what is this variable you're talking about!"
# This code will cause an error
codemon_level = 10
print(codemon_levl) # Typo: 'levl' instead of 'level'
When you run this code, Python will show an error message. This is good - it's telling you exactly what's wrong so you can fix it!
Errors are displayed in english, and usually you want to read them from bottom to top, as the last line is often the most relevant one.
On the code above, the error message would say something like
"NameError: name 'codemon_levl' is not defined"
. This means that we never attributed a value to
'codemon_levl'
, and yet, we're trying to print it.
Errors Are Your Friends
Every programmer encounters errors, even experienced ones! The difference is that experienced programmers have learned to read and understand error messages quickly. By learning about errors now, you're building an essential skill.
Exercise 2 — Syntax Errors vs Runtime Errors
There are two main types of errors in Python:
1. Syntax Errors - These happen when Python can't understand your code because you broke the rules of the Python language. It's like trying to speak French but mixing up the grammar so badly that nobody can understand you.
Python catches these before running your code.
# Syntax Error example - missing colon
if codemon_hp > 0
print("Codemon can battle")
2. Runtime Errors - These happen when your code is written correctly according to Python's rules, but something goes wrong when the code actually runs.
Python only discovers these while running your code.
# Runtime Error example - division by zero
codemon_power = 100
enemy_defense = 0
damage = codemon_power / enemy_defense # Can't divide by zero!
The syntax is correct (Python understands what you wrote), but when it tries to divide by zero, it realizes this is impossible!
Summary
Syntax errors = Python can't read your code
Runtime errors = Python can read your code, but can't execute it
Exercise 3 — Identify the Error Type
codemon_list = ["Aquachu", "Pyrochu", "Florachu"]
print(codemon_list[5])
What type of error will this cause?
Options
• Runtime error - the syntax is correct, but trying to access index 5 in a list with only 3 items fails during execution
• Syntax error - Python can't understand the code
• No error - the code will work fine
• Syntax error - lists cannot be indexed
Hint : Think about when Python will discover the problem. Can Python understand what you wrote? If yes, it's probably a runtime error.
Exercise 4 — How to Read Error Messages
When Python encounters an error, it gives you a detailed message. Let's learn to read it!
Here's an example error message:
Traceback (most recent call last):
File "codemon.py", line 3, in <module>
print(codemon_name)
NameError: name 'codemon_name' is not defined
Let's break this down:
1. Traceback - indicating there is an error
2. File and Line Number -
File "codemon.py", line 3
tells you exactly where to look
3. The Problematic Code -
print(codemon_name)
shows the line that caused the error
4. Error Type -
NameError
tells you what kind of error it is
5. Error Description -
name 'codemon_name' is not defined
explains what went wrong
Reading Error Messages: A Strategy
When you see an error:
1. Don't panic! Read the message carefully
2. Find the line number where the error occurred (if multiple files, look at the one at the bottom)
3. Look at the error type (NameError, TypeError, etc.)
4. Read the description to understand what went wrong
5. Check your code at that line and try to fix it
Exercise 5 — Common Error Types - Part 1
Let's explore the most common error types you'll encounter. We'll look at three of them first:
1. NameError - You're trying to use a variable that doesn't exist
# NameError example
print(codemon_hp) # codemon_hp was never created!
# To fix: create the variable first
codemon_hp = 100
print(codemon_hp) # Now it works!
2. TypeError - You're trying to use an operation on the wrong type of data
# TypeError example
codemon_name = "Aquachu"
codemon_level = 10
result = codemon_name + codemon_level # Can't add string and number!
# To fix: convert to the same type
result = codemon_name + str(codemon_level) # Now both are strings
3. ValueError - The type is right, but the value doesn't make sense for the operation
# ValueError example
codemon_level = int("ten") # Can't convert "ten" to a number!
# To fix: use a valid numeric string
codemon_level = int("10") # This works
Exercise 6 — Common Error Types - Part 2
Let's continue with three more common error types:
4. IndexError - You're trying to access a position in a list or string that doesn't exist
# IndexError example
codemon_team = ["Aquachu", "Pyrochu"]
print(codemon_team[5]) # There are only 2 items (indexes 0 and 1)!
# To fix: use a valid index
print(codemon_team[1]) # This works
5. KeyError - You're trying to access a dictionary key that doesn't exist
# KeyError example
codemon_stats = {"name": "Aquachu", "level": 10}
print(codemon_stats["power"]) # "power" key doesn't exist!
# To fix: use an existing key or add the key first
print(codemon_stats["name"]) # This works
6. ZeroDivisionError - You're trying to divide by zero (which is mathematically impossible)
# ZeroDivisionError example
codemon_power = 100
enemy_defense = 0
damage = codemon_power / enemy_defense # Can't divide by zero!
# To fix: check if the divisor is zero first
if enemy_defense != 0:
damage = codemon_power / enemy_defense
else:
print("Enemy defense is zero!")
Other type of errors exist, but these six are among the most common you'll encounter as you code in Python. It's a good start to recognize and understand them!
Remember These 6 Error Types
NameError = Variable doesn't exist
TypeError = Wrong type for operation
ValueError = Right type, wrong value
IndexError = List/string position doesn't exist
KeyError = Dictionary key doesn't exist
ZeroDivisionError = Trying to divide by zero
Exercise 7 — Identify the Error Type
What error will this code produce?
codemon_types = {"Aquachu": "water", "Pyrochu": "fire"}
print(codemon_types["Florachu"])
Options
• ```KeyError```
• ```IndexError```
• ```NameError```
• ```TypeError```
Hint : Think about what data structure is being used and what operation is being performed. Is it trying to access something that doesn't exist?
Exercise 8 — Match Error Types with Descriptions
Match each error type with its description:
Items to match
• NameError
• TypeError
• IndexError
• ZeroDivisionError
Definitions
• Variable is used but hasn't been created
• Operation performed on wrong data type
• Trying to access list position that doesn't exist
• Attempting to divide a number by zero
Exercise 9 — Fix the Error
This code produces a
NameError
for now. Complete it to fix the error by creating the missing variable:
# Create the missing variable
____ = ____
# Now this will work
print("Your Codémon is:", codemon_name)
Options: codemon_name codemon_level "Aquachu" Aquachu
Hint : Think about what variable is being used in the print statement and what value it should have. Remember that string values need quotes!
Exercise 10 — Predict the Error
What error will this code cause?
codemon_level = "25"
codemon_power = 100
total = codemon_level + codemon_power
Options
• ```TypeError``` - Can't add a string and an integer
• ```ValueError``` - "25" is not a valid number
• ```NameError``` - codemon_level is not defined
• No error - the code will work fine
Hint : Look carefully at the types of the variables being used. What happens when you try to perform operations with different types?
Exercise 11 — Debug the Codémon Battle System
A Codémon trainer wrote a battle system, but it's full of errors! Your mission is to fix all the bugs. The code should:
1. Create a dictionary with Codémon stats (name, level, hp)
2. Calculate damage based on level
3. Apply damage to hp
4. Display the battle result
The code has 4 different errors. Find and fix them all!
Starter code
# Buggy Codémon battle system - fix all 4 errors!
# Codémon stats
codemon = {"name": "Aquachu", "level": 15, "hp": 100}
# Calculate damage
enemy_level = "10"
damage = codemon["level"] + enemy_level
# Apply damage
codemon["hpp"] = codemon["hp"] - damage
# Display result
print(codemon_name + " took " + damage + " damage!")
print("Remaining HP:", codemon["hpp"])
Back to the course