Home Course Roadmap
PyLearn Python Course Python Errors
Lesson 39 Error Handling

Python Errors

Learn how Python errors happen, how to understand error messages, identify their causes, and write more reliable programs.

40–50 minutes Beginner Error Handling
0%
01

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 try and except.
02

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.

Example
number = 10
result = number / 0

print(result)

Python cannot divide a number by zero, so it raises an exception.

Result
ZeroDivisionError

Developer Mindset

Don't treat errors as failures. Treat them as information telling you what your program needs you to investigate.

03

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.

04

Syntax Errors

When Python cannot understand your code

A syntax error occurs when your code does not follow Python's grammar rules.

Invalid syntax
if age >= 18
    print("Adult")

The colon after the condition is missing.

Typical Error
SyntaxError: expected ':'

Another Example

Missing closing bracket
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.

05

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.

Runtime error example
numbers = [10, 20, 30]

print(numbers[5])

The syntax is valid, but index 5 does not exist in the list.

Error
IndexError: list index out of range

Runtime errors are commonly represented by exceptions.

06

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.

Logical mistake
price = 100
discount = 20

final_price = price + discount

print(final_price)
Wrong Output
120

If the intention was to subtract a discount, the correct logic would be:

Correct logic
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.

07

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.

Example exception
age = int("hello")
Exception
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.

08

Common Python Exceptions

Important errors you should recognize

Common Exceptions
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
09

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.

Example
print(username)

If username was never defined, Python raises:

Error
NameError: name 'username' is not defined

Another Common Cause

Spelling mistake
customer_name = "Ali"

print(customername)

The variable names are different. Python treats them as separate names.

10

TypeError

When an operation uses incompatible types

A TypeError occurs when an operation is not supported for the given data types.

Example
age = 25

print("Age: " + age)

You cannot directly concatenate a string and an integer using +.

Error
TypeError

Possible Solution

Convert the value
print("Age: " + str(age))

Or, even better, use an f-string:

Using an f-string
print(f"Age: {age}")
11

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.

Example
age = int("twenty")
Error
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.

12

IndexError

Accessing an unavailable position

An IndexError occurs when you attempt to access an index that does not exist.

Example
colors = ["red", "blue", "green"]

print(colors[5])

The valid indexes are: 0, 1 and 2.

Error
IndexError: list index out of range

Safe Thinking

Check the length
if len(colors) > 5:
    print(colors[5])
13

KeyError

Accessing a missing dictionary key

Example
student = {
    "name": "Ali",
    "age": 20
}

print(student["email"])

The dictionary does not contain an "email" key.

Error
KeyError: 'email'

A common alternative is to use get() when a key may not exist.

Using get()
email = student.get("email")

print(email)
Output
None
14

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.

Example
name = "Python"

name.append("!")

Strings do not have an append() method.

Error
AttributeError

append() belongs to lists, not strings.

Correct object type
names = ["Ali", "Sara"]

names.append("Ahmed")

print(names)
15

ZeroDivisionError

Understanding division by zero

Python raises ZeroDivisionError when a number is divided by zero.

Example
total = 100
students = 0

average = total / students
Error
ZeroDivisionError: division by zero

A basic defensive check can prevent the operation:

Checking first
if students != 0:
    average = total / students
else:
    print("Cannot calculate average.")
16

File-Related Errors

Problems when working with files

File operations can produce their own exceptions.

FileNotFoundError

Example
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.

17

Understanding Tracebacks

Learning to read Python's error messages

When an exception occurs, Python normally displays a traceback.

Example 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.

18

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

  1. Read the final exception name.
  2. Read the error message carefully.
  3. Find the reported line number.
  4. Inspect the variables involved.
  5. Check the data types and values.
  6. Review the previous lines of code.
  7. Reproduce the problem with a smaller example if necessary.
  8. Fix the underlying cause instead of hiding the symptom.

Example

Problem
price = "500"
quantity = 3

total = price * quantity

print(total)

Interestingly, this code does not raise an error. Python repeats the string:

Output
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.

19

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.

20

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.

21

Mini Challenge — Error Detective

Diagnose multiple Python problems

Your challenge is to inspect the following program and identify as many problems as possible.

Debug this program
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

  1. Identify the dictionary key problem.
  2. Identify the data type problem.
  3. Identify the division problem.
  4. Correct the program.
  5. Calculate the correct average.

Expected Result

Expected Output
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.

22

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?

23

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.
  • NameError usually means a name has not been defined.
  • TypeError usually involves an unsupported operation between types.
  • ValueError usually means the value itself is inappropriate.
  • IndexError occurs when an invalid sequence index is accessed.
  • KeyError occurs when a dictionary key does not exist.
  • AttributeError occurs when an object lacks the requested attribute or method.
  • ZeroDivisionError occurs when dividing by zero.
  • FileNotFoundError can 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.