Most beginner Python bugs come from the same short list of mistakes. Learn to recognise the error message each one produces and you will fix them in seconds instead of minutes.
| # | Mistake | What you see |
|---|---|---|
| 1 | Wrong indentation | IndentationError |
| 2 | Missing colon | SyntaxError: expected ':' |
| 3 | = instead of == | SyntaxError |
| 4 | Treating input() as a number | TypeError, or a wrong result |
| 5 | Joining text and numbers with + | TypeError |
| 6 | Misspelled or undefined name | NameError |
| 7 | Index past the end of a list | IndexError |
| 8 | Expecting range() to include the stop value | A loop that ends one early |
| 9 | Changing a list while looping over it | Skipped items |
| 10 | Forgetting return | None |
| 11 | Mutable default argument | Data shared between calls |
| 12 | Naming a file or variable after a built-in | Strange AttributeError or TypeError |
1. Wrong indentation
Python uses indentation to decide which lines belong to a block. Every line in a block must be indented by the same amount.
age = 20
if age >= 18:
print("Adult")IndentationError: expected an indented block after 'if' statement on line 2Fix: indent the block by four spaces, and never mix tabs with spaces. See Python syntax and indentation.
2. Missing colon
Lines that start a block (if, else, for, while, def, class) end with a colon.
for i in range(3)
print(i)SyntaxError: expected ':'Fix: add the colon at the end of the line.
3. Using = instead of ==
A single = stores a value. A double == compares two values.
score = 10
if score = 10:
print("Ten")SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?Fix: write if score == 10:. More in writing conditional statements in Python.
4. Treating input() as a number
input() always returns text, even when the user types digits.
age = input("Age: ") # the user types 20
print(age + 1)TypeError: can only concatenate str (not "int") to strA quieter version of the same bug gives a wrong answer with no error: "20" * 2 is "2020", not 40.
Fix: convert first with age = int(input("Age: ")). See getting user input in Python.
5. Joining text and numbers with +
count = 3
print("You have " + count + " messages")TypeError: can only concatenate str (not "int") to strFix: use an f-string, which converts the value for you:
count = 3
print(f"You have {count} messages")6. Misspelled or undefined names
Python names are case-sensitive, and a variable must be assigned before it is used.
total_price = 50
print(totalprice)NameError: name 'totalprice' is not defined. Did you mean: 'total_price'?Fix: check the spelling and the capital letters, and make sure the line that creates the variable runs first.
7. Index past the end of a list
Indexes start at 0, so a list of three items has indexes 0, 1, and 2.
colors = ["red", "green", "blue"]
print(colors[3])IndexError: list index out of rangeFix: the last item is colors[2], or simply colors[-1].
8. Expecting range() to include the stop value
for n in range(1, 5):
print(n) # prints 1, 2, 3, 4There is no error here, which makes the bug easy to miss. range() stops before its second argument.
Fix: to include 5, write range(1, 6). More in Python for loops explained.
9. Changing a list while looping over it
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n)
print(numbers) # [1, 2, 3]One of the 2s survives. Removing an item shifts the rest of the list to the left, so the loop steps over the next item.
Fix: build a new list instead:
numbers = [1, 2, 2, 3]
numbers = [n for n in numbers if n != 2]
print(numbers) # [1, 3]10. Forgetting return
A function that only prints its result gives nothing back to the code that called it.
def add(a, b):
print(a + b)
result = add(2, 3) # prints 5
print(result) # NoneFix: use return a + b. Printing shows a value to a person. Returning hands a value to the program. See return values in Python functions.
11. Mutable default arguments
A default value is created once, when the function is defined, not on every call.
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple")) # ['apple']
print(add_item("pear")) # ['apple', 'pear']The second call still contains the apple, because both calls share the same list.
Fix: use None as the default and create the list inside the function:
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket12. Naming a file or variable after a built-in
If you save your script as random.py, then import random loads your own file instead of Python's module:
AttributeError: module 'random' has no attribute 'randint'The same happens with variables. After list = [1, 2, 3], calling list("abc") fails with TypeError: 'list' object is not callable, because the name list now points to your data.
Fix: do not name files after standard modules (random.py, math.py, string.py), and do not name variables list, str, dict, sum, max, input, or type.
How to read the error message
When Python stops with an error, read the traceback from the bottom:
- The last line names the error type and explains the problem.
- The line above shows the file and line number where it happened.
- If that line looks correct, check the line before it. A missing bracket or quote is often reported one line late.
A fuller walkthrough is in reading Python error messages.
Mistakes by topic
Each section of this course has its own, more detailed list:
Rune AI
Key Insights
- Indent blocks with four spaces and end if, for, while, and def lines with a colon.
- Use == to compare and = to assign.
- input() returns text; convert it with int() or float() before doing maths.
- Indexes start at 0, and range() stops before its stop value.
- Do not remove items from a list while looping over it; build a new list.
- Use return to send a value back from a function, and None instead of a list as a default argument.
- Read tracebacks from the bottom: the last line names the problem.
Frequently Asked Questions
What is the most common mistake in Python?
Why does Python say my variable is not defined?
Why does input() not work with numbers in Python?
Why does my function return None?
How do I find the line that caused a Python error?
Conclusion
Every Python programmer has made all twelve of these mistakes. The skill is not avoiding them forever but recognising the error message and knowing the fix. Read the last line of the traceback first, check the line it points to, and most bugs are solved within a minute.
More in this topic
Nested Loops in Python
A nested loop is a loop inside another loop. See exactly what order the lines run in, how to work with grids and nested lists, and how to break out of both loops.
Python break, continue, and pass Explained
break exits a loop, continue skips to the next pass, and pass does nothing at all. See how each one works in for and while loops, and when to use them.
Python while Loops Explained
A while loop repeats a block for as long as a condition stays true. Learn the syntax, the while True pattern, how to validate input, and how to avoid infinite loops.