Common Python Mistakes Beginners Make

Twelve mistakes nearly every Python beginner makes, with the exact error message each one produces and the fix. Learn to recognise them and you will debug much faster.

5 min read

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.

#MistakeWhat you see
1Wrong indentationIndentationError
2Missing colonSyntaxError: expected ':'
3= instead of ==SyntaxError
4Treating input() as a numberTypeError, or a wrong result
5Joining text and numbers with +TypeError
6Misspelled or undefined nameNameError
7Index past the end of a listIndexError
8Expecting range() to include the stop valueA loop that ends one early
9Changing a list while looping over itSkipped items
10Forgetting returnNone
11Mutable default argumentData shared between calls
12Naming a file or variable after a built-inStrange 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.

pythonpython
age = 20
if age >= 18:
print("Adult")
texttext
IndentationError: expected an indented block after 'if' statement on line 2

Fix: 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.

pythonpython
for i in range(3)
    print(i)
texttext
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.

pythonpython
score = 10
if score = 10:
    print("Ten")
texttext
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.

pythonpython
age = input("Age: ")     # the user types 20
print(age + 1)
texttext
TypeError: can only concatenate str (not "int") to str

A 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 +

pythonpython
count = 3
print("You have " + count + " messages")
texttext
TypeError: can only concatenate str (not "int") to str

Fix: use an f-string, which converts the value for you:

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

pythonpython
total_price = 50
print(totalprice)
texttext
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.

pythonpython
colors = ["red", "green", "blue"]
print(colors[3])
texttext
IndexError: list index out of range

Fix: the last item is colors[2], or simply colors[-1].

8. Expecting range() to include the stop value

pythonpython
for n in range(1, 5):
    print(n)        # prints 1, 2, 3, 4

There 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

pythonpython
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:

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

pythonpython
def add(a, b):
    print(a + b)
 
result = add(2, 3)   # prints 5
print(result)        # None

Fix: 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.

pythonpython
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:

pythonpython
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

12. 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:

texttext
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:

  1. The last line names the error type and explains the problem.
  2. The line above shows the file and line number where it happened.
  3. 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

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.
RunePowered by Rune AI

Frequently Asked Questions

What is the most common mistake in Python?

Indentation errors are the most common for beginners. Python uses indentation to define blocks, so a line that is indented too little, too much, or with a tab instead of spaces stops the program with an IndentationError.

Why does Python say my variable is not defined?

A NameError means Python has not seen that exact name yet. The usual causes are a spelling or capitalisation difference, using the variable before the line that assigns it, or creating it inside a function and using it outside.

Why does input() not work with numbers in Python?

input() always returns a string. To do maths with the value, convert it first with int() for whole numbers or float() for decimals, for example age = int(input("Age: ")).

Why does my function return None?

A Python function returns None when it reaches the end without a return statement. Printing a value inside the function does not return it. Add return followed by the value you want to send back.

How do I find the line that caused a Python error?

Read the traceback from the bottom. The last line gives the error type and message, and the line above it gives the file name and line number. If that line looks fine, check the previous line for a missing bracket, quote, or colon.

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.