- Understand what errors and exceptions are in Python
- Recognize different types of errors
- Read and interpret error messages
- Understand the error traceback
Understanding Errors
Imagine you're following a recipe to bake a cake. What if the recipe says "add 2 cups of flurp"? You'd stop and say, "What's flurp? I can't continue!" That's exactly what happens in programming – when Python encounters something it doesn't understand or can't do, it raises an error.
Errors aren't your enemy – they're your friend! They tell you exactly what went wrong and where. Learning to read and understand errors is one of the most valuable skills a programmer can have. Let's demystify them!
Two Types of Problems
Python has two main categories of problems:
Types of Problems
SYNTAX ERRORS (Compile-time)
• Python can't even understand your code
• Caught BEFORE the program runs
• Like grammar mistakes in a sentence
• Example: missing colon, mismatched parentheses
EXCEPTIONS (Runtime)
• Valid syntax, but something goes wrong during execution
• Caught WHILE the program runs
• Like trying to open a door that doesn't exist
• Example: dividing by zero, file not found
Syntax Errors
Syntax errors occur when Python can't parse your code:
# Missing colon
if True
print("Hello")
# SyntaxError: expected ':'
# Mismatched parentheses
print("Hello"
# SyntaxError: unexpected EOF while parsing
# Invalid syntax
x = 5 +
# SyntaxError: invalid syntax
# Incorrect indentation
def greet():
print("Hello")
# IndentationError: expected an indented block
How Python Shows Syntax Errors
File "script.py", line 2
if True
^
SyntaxError: expected ':'
The arrow (^) points to where Python got confused!
Common Exceptions
Exceptions occur during program execution. Here are the most common ones:
TypeError - Wrong Type
# Trying to do something with incompatible types
result = "hello" + 5
# TypeError: can only concatenate str (not "int") to str
len(42)
# TypeError: object of type 'int' has no len()
ValueError - Wrong Value
# Right type, but wrong value
int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'
int("12.5") # Can't convert float string directly to int
# ValueError: invalid literal for int() with base 10: '12.5'
NameError - Unknown Name
# Using a variable that doesn't exist
print(undefined_variable)
# NameError: name 'undefined_variable' is not defined
IndexError - Bad Index
# Accessing an index that doesn't exist
my_list = [1, 2, 3]
print(my_list[10])
# IndexError: list index out of range
KeyError - Missing Key
# Accessing a dictionary key that doesn't exist
my_dict = {"name": "Alice"}
print(my_dict["age"])
# KeyError: 'age'
ZeroDivisionError - Division by Zero
# Mathematical impossibility
result = 10 / 0
# ZeroDivisionError: division by zero
FileNotFoundError - Missing File
# Trying to open a file that doesn't exist
with open("nonexistent.txt") as f:
content = f.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'
AttributeError - Missing Attribute
# Accessing an attribute that doesn't exist
"hello".append("!")
# AttributeError: 'str' object has no attribute 'append'
Reading Error Messages
Error messages have a structure – learn to read them!
Anatomy of an Error
Traceback (most recent call last):
File "main.py", line 10, in <module> ← WHERE (file/line)
result = calculate(x) ← THE CODE
File "main.py", line 5, in calculate ← DEEPER CALL
return value / divisor ← THE CODE
ZeroDivisionError: division by zero ← WHAT (error type)
← WHY (message)
Read from BOTTOM to TOP:
1. Error type (ZeroDivisionError)
2. Error message (division by zero)
3. Where it happened (line numbers, files)
Real Example
def get_item(items, index):
return items[index]
def process_data():
my_list = [1, 2, 3]
return get_item(my_list, 10)
result = process_data()
The traceback:
Traceback (most recent call last):
File "example.py", line 8, in <module>
result = process_data()
File "example.py", line 6, in process_data
return get_item(my_list, 10)
File "example.py", line 2, in get_item
return items[index]
IndexError: list index out of range
Reading it:
- Bottom:
IndexError: list index out of range- we know WHAT happened - Line 2: The actual line that failed -
items[index] - Trace up: We can see the call chain that led here
Common Error Patterns
Pattern 1: The Typo
# Did you mean 'print'?
prnt("Hello")
# NameError: name 'prnt' is not defined
# Variable name typo
user_name = "Alice"
print(username) # Missing underscore!
# NameError: name 'username' is not defined
Pattern 2: The Off-by-One
# Lists are 0-indexed!
fruits = ["apple", "banana", "cherry"]
print(fruits[3]) # Only indices 0, 1, 2 exist
# IndexError: list index out of range
Pattern 3: The None Surprise
# Many functions return None
result = [1, 2, 3].sort() # sort() modifies in place, returns None
print(result[0])
# TypeError: 'NoneType' object is not subscriptable
Pattern 4: The Type Mismatch
# User input is always a string!
age = input("Enter your age: ") # Returns "25", not 25
next_year = age + 1
# TypeError: can only concatenate str (not "int") to str
Practical Tips
Tip 1: Read the Last Line First
# When you see an error, start at the bottom!
# The last line tells you WHAT happened
# Then trace up to find WHERE
Tip 2: Copy the Error, Search Online
# If you don't understand an error:
# 1. Copy the error type and message
# 2. Search: "Python ZeroDivisionError division by zero"
# 3. Stack Overflow usually has the answer!
Tip 3: Check the Line Number
# The traceback shows line numbers
# Go to that line in your code
# Often the bug is there or one line above
Key Takeaways
Remember These Points
Syntax Errors: Python can't understand your code
Caught before running (missing colons, parentheses)
Exceptions: Code runs but something goes wrong
TypeError, ValueError, KeyError, IndexError, etc.
Read tracebacks from BOTTOM to TOP
Error type → Message → Line numbers
Error messages are helpful!
They tell you WHAT happened and WHERE
When stuck, search the error message online
What's Next?
Now you can read errors! But how do you handle them gracefully so your program doesn't crash? In the next lesson, we'll learn try and except – Python's way of catching and handling errors.
