🐛 Common Errors

Learn to identify, understand, and fix the most common programming errors.

What you'll learn:

  • The difference between syntax errors and logic errors
  • How to read and understand error messages
  • Common syntax errors and how to fix them
  • Common logic errors and debugging strategies

Two Types of Errors

🔴 Syntax Errors

What: Mistakes in how you write the code - breaking Python's grammar rules.

When detected: Before the program runs. Python won't even start.

Examples:

  • Missing colons after if/for/while
  • Incorrect indentation
  • Unclosed brackets or quotes
  • Misspelled keywords

Good news: Python tells you exactly where the error is!

🟡 Logic Errors

What: Code runs without crashing, but produces wrong results.

When detected: Only when you test and check the output.

Examples:

  • Using wrong operator (+ instead of -)
  • Off-by-one errors in loops
  • Wrong comparison (> instead of >=)
  • Variables in wrong order

Challenge: No error message - you must find them yourself!

Learning Path

Follow these activities in order.

Key Vocabulary

syntax error

Breaking Python's grammar rules. The code cannot run at all.

logic error

Code runs but gives wrong results. Also called a "bug".

runtime error

Error that occurs while the program is running (e.g., dividing by zero).

debugging

The process of finding and fixing errors in code.

traceback

Python's error report showing where and what went wrong.

exception

A runtime error that stops the program (e.g., TypeError, ValueError).

Common Syntax Errors

syntax_errors.py
# ❌ Missing colon after if/for/while
if x > 5      # SyntaxError! Should be: if x > 5:

# ❌ Incorrect indentation
for i in range(3):
print(i)        # IndentationError! Should be indented

# ❌ Unclosed string
name = "Alice   # SyntaxError! Missing closing quote

# ❌ Unclosed brackets
numbers = [1, 2, 3  # SyntaxError! Missing ]

# ❌ Using = instead of == in comparison
if x = 5:       # SyntaxError! Should be: if x == 5:

# ❌ Misspelled keywords
pritn("Hello")  # NameError! Should be: print

Common Logic Errors

logic_errors.py
# ❌ Off-by-one error (wrong range)
for i in range(1, 5):  # Goes 1,2,3,4 not 1,2,3,4,5!
    print(i)

# ❌ Wrong operator
average = total + count  # Should be total / count

# ❌ Wrong comparison
if score > 50:         # Misses exactly 50! Should be >= 50

# ❌ Variable not updated
total = 0
for num in numbers:
    total + num          # Should be: total = total + num

# ❌ Initialising inside loop
for num in numbers:
    total = 0            # Resets every iteration! Move before loop
    total = total + num

# ❌ Print inside loop (meant for after)
for num in numbers:
    total = total + num
    print(total)         # Prints every iteration! Move outside loop