Common Types of Errors
Overview
Python programs can fail due to syntax, runtime, or logical errors. You'll explore how to identify each type, understand their causes, and develop strategies to prevent them before they occur, building more reliable code from the start.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Syntax errors: Mistakes in code structure that prevent Python from running.
- Runtime errors: Errors that occur while your program is executing.
- Logical errors: Bugs where code runs but produces wrong results.
- How to identify each type: Recognizing error patterns and messages.
- Prevention strategies: Techniques to avoid common errors.
Three Main Types of Errors
Python errors fall into three main categories. Understanding these categories helps you debug more efficiently:
1. Syntax Errors
Code structure mistakes that Python catches before running. These are the easiest to fix.
2. Runtime Errors
Errors that occur while your program runs. Python stops execution when these happen.
3. Logical Errors
Code runs without crashing but produces incorrect results. These are the hardest to find.
Syntax Errors
Syntax errors occur when your code doesn't follow Python's rules. Python catches these before your program runs, so they're the first errors you'll encounter.
# Missing colon
if x > 5 # SyntaxError: expected ':'
# Missing closing parenthesis
print("Hello" # SyntaxError: unexpected EOF
# Incorrect indentation
def my_function():
print("Hello") # IndentationError: expected an indented block
# Misspelled keyword
whle True: # SyntaxError: invalid syntax
print("Loop")
How to Fix Syntax Errors
- Read the error message carefully - it tells you the line number
- Check for missing colons, parentheses, brackets, or quotes
- Verify indentation is correct (Python is strict about this!)
- Check for typos in keywords like
if,def,while - Use a code editor with syntax highlighting to catch errors early
Runtime Errors
Runtime errors (also called exceptions) occur while your program is running. The code syntax is correct, but something goes wrong during execution.
# ZeroDivisionError
result = 10 / 0 # Can't divide by zero!
# NameError
print(undefined_variable) # Variable doesn't exist
# TypeError
number = "5"
result = number + 10 # Can't add string and integer
# IndexError
my_list = [1, 2, 3]
print(my_list[10]) # Index out of range
# KeyError
my_dict = {"name": "Alice"}
print(my_dict["age"]) # Key doesn't exist
# FileNotFoundError
with open("nonexistent.txt", "r") as f:
content = f.read() # File doesn't exist
Common Runtime Error Types
| Error Type | When It Happens | Example |
|---|---|---|
ZeroDivisionError |
Dividing by zero | 10 / 0 |
NameError |
Using undefined variable | print(x) when x doesn't exist |
TypeError |
Wrong data type operation | "5" + 10 |
IndexError |
List index out of range | my_list[100] when list has 3 items |
KeyError |
Dictionary key doesn't exist | my_dict["missing"] |
ValueError |
Wrong value type | int("hello") |
Logical Errors
Logical errors are the trickiest type. Your code runs without crashing, but it produces incorrect results. These require careful thinking to find.
# This code runs but gives wrong answer
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers) - 1 # Bug: subtracting 1 makes average wrong!
# Should return 5.0, but returns 4.0
result = calculate_average([4, 5, 6])
print(result)
Finding Logical Errors
Logical errors require:
- Understanding what the code should do
- Testing with known inputs and expected outputs
- Tracing through code step-by-step
- Using print statements or a debugger to see what's happening
- Writing tests to catch these errors early
Preventing Errors
While you can't avoid all errors, you can prevent many of them:
Write Clear Code
Use descriptive variable names and write comments explaining complex logic.
Test Incrementally
Test your code as you write it, not just at the end.
Handle Edge Cases
Think about what happens with empty lists, zero values, or None.
Use Type Hints
Python's type hints help catch type-related errors early.
Write Tests
Automated tests catch errors before they reach users.
Summary
In this lesson, you learned:
- Syntax errors: Caught before execution, usually easy to fix
- Runtime errors: Occur during execution, Python stops and shows error
- Logical errors: Code runs but produces wrong results, hardest to find
- Common error types: ZeroDivisionError, NameError, TypeError, IndexError, KeyError, ValueError
- Prevention: Write clear code, test incrementally, handle edge cases
Remember
Errors are learning opportunities! Each error teaches you something about how Python works. Don't be discouraged by errors—every programmer encounters them constantly. The key is learning to identify and fix them efficiently.
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: Error Types
What are the three main types of errors in Python? Give an example of each and explain how they differ.
Exercise 2: Common Errors
Name three common runtime errors and explain when each one occurs. How would you prevent or handle each?