The 10 Errors You'll See Most Often

Every Python beginner writes these. They're not signs of failure โ€” they're part of learning.

1. IndentationError

if x > 0:
print("positive")  # โœ— Missing indent

Fix: Indent with 4 spaces: print("positive")

2. SyntaxError: invalid syntax

if x > 0
    print("positive")  # โœ— Missing colon

Fix: Add : at the end of the if statement.

3. NameError: name 'x' is not defined

print(y)  # y was never created

Fix: Define the variable first. Check for typos in the name.

4. TypeError: unsupported operand type

"5" + 3  # โœ— can't add str and int

Fix: Convert: int("5") + 3 gives 8, or "5" + str(3) gives "53".

5. IndexError: list index out of range

lst = [1, 2, 3]
print(lst[5])  # โœ— index 5 doesn't exist

Fix: Check len(lst) before accessing. Use negative indices for end: lst[-1].

6. KeyError

d = {"a": 1}
print(d["b"])  # โœ— 'b' not in dict

Fix: Use d.get("b") (returns None if missing) or check with if "b" in d.

7. ValueError

int("hello")  # โœ— can't convert non-number

Fix: Validate before converting, or use try/except.

8. ZeroDivisionError

10 / 0  # โœ— math undefined

Fix: Check for zero: if n != 0: result = 10 / n

9. AttributeError

s = "hello"
s.reverse()  # โœ— strings don't have .reverse()

Fix: Use s[::-1] for strings. .reverse() is for lists.

10. UnboundLocalError

count = 0
def increment():
    count += 1   # โœ— can't modify global without declaring

Fix: Add global count inside the function, or pass/return the value.

Debugging Method

  1. Read the error message bottom-up
  2. Look at the line number
  3. Check that variables and functions exist and are spelled correctly
  4. Add print() to check values
  5. Simplify the code until it works, then add back features

Practise Fixing Errors in PyForm

PyForm shows clear error messages with line highlighting. Learn to debug faster.

Open PyForm โ†’