Python Errors
Learn how Python errors happen, how to understand error messages, identify their causes, and write more reliable programs.
Learning Objectives
What you will learn in this lesson
- Understand what programming errors are.
- Differentiate syntax, runtime and logical errors.
- Understand Python exceptions.
- Recognize common Python exception types.
- Read and understand Python tracebacks.
- Identify the real cause of an error.
- Understand why an error occurs instead of simply memorizing messages.
- Prepare for structured error handling with
tryandexcept.
What Are Errors?
Understanding problems in programs
An error occurs when Python cannot successfully perform what your program asks it to do.
Errors are a normal part of programming. Even experienced developers encounter them every day.
number = 10
result = number / 0
print(result)
Python cannot divide a number by zero, so it raises an exception.
ZeroDivisionError
Developer Mindset
Don't treat errors as failures. Treat them as information telling you what your program needs you to investigate.
Why Errors Matter
Reliable programs require error awareness
A small error can prevent an entire application from working correctly.
Consider an ecommerce application. If a calculation fails while processing an order, the application may not be able to generate the customer's invoice.
Good Programs Should
- Detect problems.
- Provide useful information.
- Handle expected failures safely.
- Avoid silently producing incorrect results.
- Help developers locate the cause quickly.
Understanding errors is therefore an essential programming skill, not an optional topic.
Syntax Errors
When Python cannot understand your code
A syntax error occurs when your code does not follow Python's grammar rules.
if age >= 18
print("Adult")
The colon after the condition is missing.
SyntaxError: expected ':'
Another Example
numbers = [1, 2, 3
Python detects the problem before the program can execute normally.
Remember
Syntax errors are usually fixed by correcting the structure or grammar of the code.
Runtime Errors
Errors that occur while a program runs
A runtime error occurs after Python has successfully understood the syntax but encounters a problem while executing the program.
numbers = [10, 20, 30]
print(numbers[5])
The syntax is valid, but index 5 does
not exist in the list.
IndexError: list index out of range
Runtime errors are commonly represented by exceptions.
Logical Errors
When the program runs but gives the wrong result
A logical error is different from a syntax or runtime error.
The program runs successfully, but the result is incorrect because the logic is wrong.
price = 100
discount = 20
final_price = price + discount
print(final_price)
120
If the intention was to subtract a discount, the correct logic would be:
final_price = price - discount
print(final_price)
Important
Logical errors can be harder to find because Python may not display an error message at all.
Exceptions
Python's way of reporting runtime problems
An exception is an event that occurs during program execution and interrupts the normal flow of the program.
age = int("hello")
ValueError: invalid literal for int()
Python creates an exception object describing what went wrong.
In the next lesson, you will learn how to respond
to these exceptions using try and
except.
Common Python Exceptions
Important errors you should recognize
| Exception | Typical Cause |
|---|---|
| SyntaxError | Invalid Python syntax |
| NameError | Using an undefined name |
| TypeError | Incompatible data types |
| ValueError | Invalid value for an operation |
| IndexError | Invalid sequence index |
| KeyError | Missing dictionary key |
| AttributeError | Object does not have requested attribute |
| ZeroDivisionError | Division by zero |
| FileNotFoundError | Requested file does not exist |
| PermissionError | Insufficient file permissions |
NameError
Using a name Python does not know
A NameError occurs when Python cannot
find a variable, function or other name that your
code is trying to use.
print(username)
If username was never defined, Python
raises:
NameError: name 'username' is not defined
Another Common Cause
customer_name = "Ali"
print(customername)
The variable names are different. Python treats them as separate names.
TypeError
When an operation uses incompatible types
A TypeError occurs when an operation
is not supported for the given data types.
age = 25
print("Age: " + age)
You cannot directly concatenate a string and
an integer using +.
TypeError
Possible Solution
print("Age: " + str(age))
Or, even better, use an f-string:
print(f"Age: {age}")
ValueError
When the type is valid but the value is not
A ValueError occurs when a function
receives a value of the correct general type,
but the value itself is inappropriate.
age = int("twenty")
ValueError: invalid literal for int()
The problem is not that the input is a string.
The problem is that "twenty" cannot
be converted into an integer.
Think Carefully
TypeError often means the operation received an inappropriate type. ValueError often means the type is acceptable but the actual value is not.
IndexError
Accessing an unavailable position
An IndexError occurs when you attempt
to access an index that does not exist.
colors = ["red", "blue", "green"]
print(colors[5])
The valid indexes are:
0, 1 and 2.
IndexError: list index out of range
Safe Thinking
if len(colors) > 5:
print(colors[5])
KeyError
Accessing a missing dictionary key
student = {
"name": "Ali",
"age": 20
}
print(student["email"])
The dictionary does not contain an
"email" key.
KeyError: 'email'
A common alternative is to use
get() when a key may not exist.
email = student.get("email")
print(email)
None
AttributeError
Using an attribute or method that does not exist
An AttributeError occurs when an object
does not have the attribute or method you are trying
to access.
name = "Python"
name.append("!")
Strings do not have an append() method.
AttributeError
append() belongs to lists, not strings.
names = ["Ali", "Sara"]
names.append("Ahmed")
print(names)
ZeroDivisionError
Understanding division by zero
Python raises ZeroDivisionError when
a number is divided by zero.
total = 100
students = 0
average = total / students
ZeroDivisionError: division by zero
A basic defensive check can prevent the operation:
if students != 0:
average = total / students
else:
print("Cannot calculate average.")
File-Related Errors
Problems when working with files
File operations can produce their own exceptions.
FileNotFoundError
with open("missing.txt", "r") as file:
content = file.read()
If the file does not exist, Python raises
FileNotFoundError.
PermissionError
Python may raise PermissionError when
the operating system prevents the program from
accessing a file or directory.
File Errors
These errors become especially important when building applications that read user files, reports, configuration files or datasets.
Understanding Tracebacks
Learning to read Python's error messages
When an exception occurs, Python normally displays a traceback.
Traceback (most recent call last):
File "app.py", line 8, in <module>
result = numbers[5]
IndexError: list index out of range
A traceback contains useful information such as:
- The file where the error occurred.
- The line number involved.
- The code associated with the failure.
- The exception type.
- A description of the problem.
Read From the Bottom
When examining a traceback, the final line often tells you the most important information: the exception type and its message.
Finding the Cause of an Error
A practical debugging mindset
When Python displays an error, don't immediately change random lines of code.
Follow a systematic process.
Step-by-Step Method
- Read the final exception name.
- Read the error message carefully.
- Find the reported line number.
- Inspect the variables involved.
- Check the data types and values.
- Review the previous lines of code.
- Reproduce the problem with a smaller example if necessary.
- Fix the underlying cause instead of hiding the symptom.
Example
price = "500"
quantity = 3
total = price * quantity
print(total)
Interestingly, this code does not raise an error. Python repeats the string:
500500500
This is an example of why understanding the data type and intended logic matters. The program technically runs, but it may not be doing what the developer intended.
Key Lesson
Not every programming problem produces an exception. Some problems are logical errors.
Common Mistakes
Habits that make debugging harder
1. Ignoring the error message
Error messages often contain the exact clue you need to find the problem.
2. Fixing the wrong line
The line reported by Python may be where the problem becomes visible, but the underlying cause can sometimes occur earlier.
3. Changing too much code at once
Make small changes and test again. This makes it easier to identify which change solved the problem.
4. Confusing TypeError and ValueError
Always inspect both the type and the actual value involved in the operation.
5. Hiding errors instead of understanding them
Error handling should make applications safer. It should not be used to silently ignore serious programming mistakes.
Practice Exercises
Train your debugging skills
Exercise 1 — Find the Syntax Error
if age > 18
print("Adult")
Identify and correct the syntax error.
Exercise 2 — Find the NameError
name = "Ali"
print(nam)
Identify why Python raises a
NameError.
Exercise 3 — Find the TypeError
age = 20
print("Age: " + age)
Fix the program using an f-string.
Exercise 4 — Find the ValueError
number = int("abc")
Explain why the conversion fails.
Exercise 5 — Find the IndexError
numbers = [10, 20, 30]
print(numbers[3])
Identify the valid indexes and correct the program.
Exercise 6 — Find the KeyError
user = {
"name": "Sara"
}
print(user["email"])
Fix the program using get().
Exercise 7 — Find the ZeroDivisionError
total = 500
items = 0
average = total / items
Prevent the division when the number of items is zero.
Exercise 8 — Logical Error
length = 10
width = 5
area = length + width
print(area)
The program runs, but the result is incorrect. Fix the logic.
Mini Challenge — Error Detective
Diagnose multiple Python problems
Your challenge is to inspect the following program and identify as many problems as possible.
students = [
{"name": "Ali", "marks": "85"},
{"name": "Sara", "marks": "92"},
{"name": "Ahmed", "marks": "78"}
]
total = 0
for student in students:
total += student["mark"]
average = total / 0
print("Average:", average)
Your Tasks
- Identify the dictionary key problem.
- Identify the data type problem.
- Identify the division problem.
- Correct the program.
- Calculate the correct average.
Expected Result
Average: 85.0
Challenge Goal
This exercise teaches an important professional skill: one program can contain multiple different problems, and you must identify each one separately.
Quick Knowledge Check
Test what you learned
1. What is a syntax error?
2. What type of problem occurs when a program runs but produces the wrong result?
3. Which exception occurs when a variable has not been defined?
4. Which exception commonly occurs when incompatible types are used together?
5. Which exception occurs when a value cannot be converted into the requested form?
6. What happens when you access a list index that does not exist?
7. Which exception occurs when a dictionary key does not exist?
8. Which exception occurs when you divide by zero?
9. What does a traceback help you understand?
10. What should you usually do first when you see an error?
Lesson Summary
What you should remember
Key Takeaways
- Errors are a normal and useful part of programming.
- Syntax errors occur when Python cannot understand the code structure.
- Runtime errors occur while the program is executing.
- Logical errors produce incorrect results even though the program may run successfully.
- Runtime problems are commonly represented by Python exceptions.
-
NameErrorusually means a name has not been defined. -
TypeErrorusually involves an unsupported operation between types. -
ValueErrorusually means the value itself is inappropriate. -
IndexErroroccurs when an invalid sequence index is accessed. -
KeyErroroccurs when a dictionary key does not exist. -
AttributeErroroccurs when an object lacks the requested attribute or method. -
ZeroDivisionErroroccurs when dividing by zero. -
FileNotFoundErrorcan occur when a requested file does not exist. - A traceback provides valuable information for diagnosing exceptions.
- Good developers investigate the cause instead of simply hiding the error.
In the next lesson, you will learn how to handle
these exceptions gracefully using
try and except.
Excellent work!
You've completed Python Errors. Mark this lesson complete and continue your journey.