Table of Contents
Overview
This chapter focuses on common mistakes beginners make in Python and how to fix them. You will see short examples of each error, what the error message usually looks like, and how to correct your code.
Use this chapter as a checklist when your program “mysteriously” doesn’t work.
Syntax and Typing Mistakes
These errors happen before your code even runs. Python stops and shows an error message.
Missing or extra colons `:`
Colons appear in several places, including:
if,elif,elsefor,whiledef(functions)class(in OOP)
Common mistake:
if x > 10
print("Too big")Typical error:
SyntaxError: expected ':'
Correct:
if x > 10:
print("Too big")Similarly:
for i in range(5) # WRONG
print(i)
while n > 0 # WRONG
n = n - 1Need colons:
for i in range(5):
print(i)
while n > 0:
n = n - 1Wrong indentation or inconsistent spaces
Python uses indentation to define blocks. Common mistakes:
- Forgetting to indent inside a block
- Mixing tabs and spaces
- Indenting too little or too much
Example:
if age >= 18:
print("You are an adult") # WRONG: not indentedTypical error:
IndentationError: expected an indented block- Or
IndentationError: unindent does not match any outer indentation level
Correct:
if age >= 18:
print("You are an adult")Another common case: extra indentation where it’s not needed.
print("Hello") # WRONG if not inside any blockKeep everything aligned consistently, and prefer 4 spaces per indent (no tabs).
Using `=` instead of `==` in conditions
= is assignment.
== is comparison.
Common mistake:
if x = 5: # WRONG
print("x is 5")Typical error:
SyntaxError: invalid syntax
Correct:
if x == 5:
print("x is 5")
Remember: only use = when storing a value, == when comparing values.
Unclosed quotes or parentheses
Forgetting to close:
'or"for strings(,[,{for groups
Example:
name = "Alice # WRONG: no closing quote
print("Hello", name)Or:
print("Result is", (2 + 3 # WRONG: missing closing parenthesisTypical errors:
SyntaxError: EOL while scanning string literalSyntaxError: unexpected EOF while parsing
Correct:
name = "Alice"
print("Hello", name)
print("Result is", (2 + 3))When you see these errors, carefully count your opening and closing characters.
Name and Variable Errors
These errors usually appear as NameError and often mean you typed something wrong or used it too early.
Misspelled variable or function names
Python is case-sensitive and spelling-sensitive.
Example:
userName = "Alex"
print(username) # WRONG: lowercase nTypical error:
NameError: name 'username' is not defined
Correct:
userName = "Alex"
print(userName)Or, better, choose simple names and be consistent:
username = "Alex"
print(username)Same issue with built-in names:
pritn("Hi") # WRONGTypical error:
NameError: name 'pritn' is not defined
Correct:
print("Hi")Using a variable before assigning it
Example:
print(total) # WRONG: total not defined yet
total = 10Typical error:
NameError: name 'total' is not defined
Correct:
total = 10
print(total)Or inside conditions and loops:
if done:
print("Finished") # WRONG if 'done' was never definedDefine variables before you use them.
Overwriting built-in names
Beginners sometimes use variable names that are already used by Python.
Example:
print = "hello" # Overwrites the built-in print function
print("Hi") # Now this is a string, not a functionTypical error later:
TypeError: 'str' object is not callable
Similar issues:
list = [1, 2, 3]
dict = {}
These hide the built-in list and dict types.
Avoid using names like list, dict, str, int, input, print for your own variables.
Type-Related Mistakes
These errors involve mixing incompatible types.
Adding numbers and strings directly
User input is a string by default. Beginners often try:
age = input("Enter your age: ")
years = 5
print("In 5 years you will be " + age + years) # WRONGTypical error:
TypeError: can only concatenate str (not "int") to str
Correct approaches:
- Convert the number to a string:
print("In 5 years you will be " + age + str(years))- Or better, convert
ageto a number and use commas:
age = int(input("Enter your age: "))
years = 5
print("In 5 years you will be", age + years)Related issue:
result = "Answer: " + 10 # WRONG
Always check: are you combining str and int/float?
Forgetting to convert input to numbers
Example:
x = input("Enter a number: ")
y = input("Enter another number: ")
print("Sum:", x + y) # WRONG if you expect numeric sum
If x = "2" and y = "3", the output is:
Sum: 23
Because strings are concatenated.
Correct:
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
print("Sum:", x + y)For decimals:
x = float(input("Enter a decimal number: "))Dividing by zero
Example:
x = int(input("Enter a number: "))
print(10 / x) # If x is 0Typical error:
ZeroDivisionError: division by zero
Avoid by checking the value:
x = int(input("Enter a number: "))
if x != 0:
print(10 / x)
else:
print("Cannot divide by zero.")Logic and Condition Mistakes
These errors don’t always stop the program, but they make it do the wrong thing.
Using `=` instead of comparison in conditions (logical mistake)
Sometimes this is caught as a syntax error (as shown before), but beginners may also mix up “assignment” and “comparison” conceptually.
Wrong idea:
# "Set x to 5 in the if" – this is not how if works!
if x = 5: # syntactically wrong AND logically wrong
...Remember:
- Use
x = 5to givexa value. - Use
x == 5to check the value.
Wrong use of `and` / `or` / `not`
Example: age range check.
Common wrong attempts:
age = 20
# WRONG: this does not do what most people expect
if age >= 18 or age <= 30:
print("Age between 18 and 30")
With or, almost any age will satisfy one of the conditions.
Correct:
if age >= 18 and age <= 30:
print("Age between 18 and 30")Or shorter:
if 18 <= age <= 30:
print("Age between 18 and 30")
Another mistake: placing not incorrectly.
logged_in = False
# WRONG: double negative confusion
if not logged_in == True:
print("Please log in")This is confusing. Prefer:
if not logged_in:
print("Please log in")Misusing `if` / `elif` / `else`
Common mistake: using separate if statements where elif is needed.
Example:
score = 85
if score >= 90:
grade = "A"
if score >= 80:
grade = "B" # OVERWRITES grade, even if it was "A"Correct:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif ensures only one block runs in that chain.
Another mistake: unreachable elif or else:
if x > 10:
...
elif x > 20: # This can never be true if x > 10 was already true
...Think carefully about the order of your conditions.
Loop Mistakes
These often cause infinite loops or loops that run the wrong number of times.
Infinite `while` loops (condition never changes)
Example:
count = 0
while count < 5:
print(count)
# Forgot to change count!
This prints 0 forever.
Correct:
count = 0
while count < 5:
print(count)
count = count + 1Always ask: “Does something inside the loop eventually make the condition false?”
Looping the wrong number of times with `range()`
Beginners often get confused by range(), especially off-by-one errors.
Example:
# Want to print numbers 1 to 5
for i in range(1, 5):
print(i)
This prints 1 2 3 4, because range(1, 5) stops before 5.
Correct:
for i in range(1, 6):
print(i)
Another mistake: assuming range(n) includes n.
for i in range(5):
print(i)
This prints 0 1 2 3 4, not 5.
Misusing `break` and `continue`
break exits the whole loop. continue skips to the next iteration.
Common mistake: putting break too early.
for i in range(5):
print(i)
break # Loop stops after first iterationIf you meant to stop only under a condition:
for i in range(5):
print(i)
if i == 3:
break
Or using continue in a way that accidentally creates an infinite loop in a while:
count = 0
while count < 5:
if count == 2:
continue # WRONG: count never increases when it's 2
print(count)
count += 1
Here, when count becomes 2, the program keeps hitting continue and never increments count.
Correct: change the order:
count = 0
while count < 5:
if count == 2:
count += 1
continue
print(count)
count += 1Working with Collections (Lists, Strings, etc.)
Using the wrong index or going out of range
Every list and string in Python is zero-indexed:
- First item: index 0
- Last item: index
len(sequence) - 1
Common mistake:
numbers = [10, 20, 30]
print(numbers[3]) # WRONG, only indices 0,1,2 existTypical error:
IndexError: list index out of range
Correct:
print(numbers[0]) # 10
print(numbers[1]) # 20
print(numbers[2]) # 30Similar issues when looping:
names = ["Ana", "Bob", "Cara"]
for i in range(0, len(names) + 1): # WRONG: +1 causes out of range
print(names[i])Correct:
for i in range(0, len(names)):
print(names[i])Or simpler:
for name in names:
print(name)Confusing list methods like `append` and `extend`
Common mistake:
nums = [1, 2, 3]
nums = nums.append(4) # WRONG
print(nums)
append changes the list in place and returns None, so nums becomes None.
Correct:
nums = [1, 2, 3]
nums.append(4)
print(nums) # [1, 2, 3, 4]
Another confusion: append vs extend.
nums = [1, 2, 3]
nums.append([4, 5])
print(nums) # [1, 2, 3, [4, 5]] (a list inside a list)If you wanted to add 4 and 5 as separate elements:
nums = [1, 2, 3]
nums.extend([4, 5])
print(nums) # [1, 2, 3, 4, 5]Input/Output and Printing Mistakes
Forgetting parentheses with `print` in Python 3
If you have seen Python 2 examples online, you might write:
print "Hello" # WRONG in Python 3Typical error:
SyntaxError: Missing parentheses in call to 'print'
Correct:
print("Hello")Printing the wrong thing (logic vs syntax)
Example: trying to print the result of a calculation but printing the expression as a string.
x = 2
y = 3
print("x + y") # Prints the text "x + y", not 5Correct:
print(x + y) # 5
print("x + y =", x + y) # x + y = 5Function and Scope Mistakes
(Details of functions and scope appear in their own chapters; here we focus on typical beginner errors.)
Calling a function before defining it (in the wrong place)
Example in a script:
greet()
def greet():
print("Hello")Typical error:
NameError: name 'greet' is not defined
Correct:
def greet():
print("Hello")
greet()Python executes top to bottom in a file; define functions before you call them (except in some advanced patterns).
Forgetting to use `return`
Example:
def add(a, b):
result = a + b # WRONG: no return
# ...
sum_value = add(2, 3)
print(sum_value)Typical result:
sum_valueisNone
Correct:
def add(a, b):
result = a + b
return result
sum_value = add(2, 3)
print(sum_value) # 5Or shorter:
def add(a, b):
return a + bFile and Path Mistakes (Basic)
(There is a full chapter on working with files; here are just a few beginner errors.)
Using the wrong file path or assuming the wrong folder
Common mistake:
f = open("data.txt")Typical error:
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Reasons:
data.txtis not in the same folder as your script.- You are running the script from a different working directory.
Quick checks:
- Is the file in the right folder?
- Is the name exactly correct (including case and extension)?
- Do you need a full/absolute path?
Example with a relative path:
f = open("files/data.txt") # if data.txt is inside a "files" folder
Always close files (or use with), but the main beginner issue is wrong locations/name.
Misreading and Ignoring Error Messages
A very common beginner error is not reading the error message carefully at all.
Typical mistake:
- Only seeing “something went wrong” and randomly changing code.
Better approach:
- Look at the type of error (e.g.
SyntaxError,NameError,TypeError). - Look at the line number Python points to.
- Read the message in plain English.
Example:
values = [1, 2, 3]
print(values[3])Error:
IndexError: list index out of rangeThis tells you:
- You tried to take an index from a list.
- That index does not exist.
Use error messages as hints, not enemies.
How to Practice Avoiding These Errors
- Type out the wrong examples from this chapter, run them, and see the errors.
- Then fix them and see how the error disappears.
- When you get a new error in your own code:
- Compare it with the patterns you learned here.
- Ask: Is this a name issue? Type issue? Index issue? Logic issue?
Over time, these “beginner errors” become rare, and when they appear, you will know exactly where to look.