KAHIBARO Bookshelves
Discord Login Register

11.1. Types of errors

The Three Main Types of Errors in Python

When you write Python programs, you’ll usually encounter three broad kinds of errors:

  1. Syntax errors
  2. Runtime errors (also called exceptions)
  3. Logic errors

Understanding the differences between them will make it much easier to fix your programs.

1. Syntax Errors

A syntax error means “your code is not valid Python grammar.”
Python cannot even start running the program because it doesn’t understand how it’s written.

Think of this like writing a sentence with completely broken grammar: the reader can’t even guess what you meant.

Common causes of syntax errors

Typical beginner mistakes include:

  • Forgetting a colon : after:
    • if, elif, else
    • for, while
    • def, class
  • Missing or extra parentheses, quotes, or brackets
  • Using = instead of == inside conditions
  • Incorrect indentation in places where Python expects a block

Examples:

# Missing colon
if x > 10
    print("Too big")
# Unmatched parenthesis
print("Hello"
# Wrong use of '=' in a condition
if x = 5:
    print("x is 5")

Python will stop immediately and show a message like:

  File "example.py", line 1
    if x > 10
             ^
SyntaxError: invalid syntax

Key points about syntax errors:

  • They happen before any code runs.
  • The error message usually points to the line (or near the line) where Python got confused.
  • Fixing them is often about checking:
    • colons
    • parentheses
    • quotes
    • indentation

2. Runtime Errors (Exceptions)

A runtime error (or exception) occurs while your program is running.
The code is syntactically correct, so Python starts to run it, but something goes wrong during execution.

Example:

x = 10 / 0       # Division by zero
print("Done")

This code has no syntax errors, but when Python executes 10 / 0, it crashes with:

ZeroDivisionError: division by zero

Common runtime errors include:

  • ZeroDivisionError – dividing by zero
  result = 5 / 0
  • NameError – using a variable that hasn’t been defined
  print(score)  # score was never assigned
  • TypeError – using the wrong type for an operation
  result = "5" + 3  # can't add string and int
  • ValueError – correct type, but invalid value
  number = int("hello")  # "hello" can't be turned into an int
  • IndexError – using an index that’s out of range in a list or string
  numbers = [10, 20, 30]
  print(numbers[5])  # list only has 3 elements
  • KeyError – using a dictionary key that does not exist
  ages = {"Alice": 25}
  print(ages["Bob"])  # "Bob" is not a key

Key points about runtime errors:

  • The program starts running, but stops at the line where the error happens.
  • Python shows:
    • the type of error (e.g., TypeError)
    • a message explaining what went wrong
    • usually a traceback telling you which line caused it
  • These can often be prevented by checking values or using try/except (covered in another section of this chapter).

3. Logic Errors

A logic error means “your program runs without crashing, but it doesn’t do what you intended.”
Python is perfectly happy with your code – but the idea behind the code is wrong.

Example:

You want to calculate the average of two numbers:

a = 10
b = 20
average = a + b / 2
print(average)

This runs and prints:

20.0

But the real average of 10 and 20 is $ (10 + 20) / 2 = 15 $.
The problem is operator precedence: b / 2 happens first, so the expression is actually:

average = a + (b / 2)  # 10 + (20 / 2) = 20

The correct version:

average = (a + b) / 2

Other examples of logic errors:

  • Using < when you meant <=
  • Using and when you meant or in a condition
  • Updating the wrong variable inside a loop
  • Off-by-one mistakes, like looping 9 times when you intended 10

Key points about logic errors:

  • The program doesn’t crash.
  • Python usually doesn’t give any error message.
  • You discover them by:
    • testing your program with known inputs
    • checking whether the outputs match your expectations
    • adding print statements or using a debugger to inspect values

Comparing the Three Types

Here is a quick comparison:

  • Syntax errors
    • When: Before the program runs
    • Symptom: Program won’t start; SyntaxError
    • Cause: Invalid Python structure (missing colons, bad indentation, etc.)
    • Fix: Correct the code so it follows Python’s rules
  • Runtime errors (exceptions)
    • When: During execution
    • Symptom: Program starts but then crashes with an error message
    • Cause: Something goes wrong with a particular operation (e.g., divide by zero)
    • Fix: Handle special cases, validate input, use try/except when appropriate
  • Logic errors
    • When: During execution
    • Symptom: Program runs to the end, but output is wrong
    • Cause: The algorithm or conditions don’t match what you intended
    • Fix: Rethink the logic, add tests, inspect intermediate values

Practice: Spot the Error Type

For each of these, decide which kind of error it would cause:

  1. :::code
    if x > 10
    print("Big")
  2. :::code
    x = "10"
    y = 5
    print(x * y)
  3. :::code
    total = 0
    numbers = [1, 2, 3]
    for n in numbers:
    total = total + 1
    print(total) # You wanted the sum of the numbers
  4. :::code
    items = [10, 20, 30]
    print(items[3])

Answers (don’t peek until you’ve tried):

  1. Syntax error (missing colon)
  2. No error in Python: this runs and prints "1010101010" – if you expected 15, it’s a logic error
  3. Logic error (you’re counting items, not summing them)
  4. Runtime error: IndexError (index 3 is out of range)

Being able to quickly recognize which type of error you’re dealing with is an important debugging skill.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms