Lesson 16 of 18 · 3 min
Common Mistakes and Error Messages
Every programmer makes these mistakes. Study them so you know how to fix them.
SyntaxError — Code Written Incorrectly
# MISTAKE: Forgetting quotes around a string print(Hello World) # Python thinks Hello and World are variable names
Error: SyntaxError: invalid syntax
# FIX: Wrap text in quotes
print("Hello World") # now Python knows it is text# MISTAKE: Using = instead of == for comparison
x = 5
if x = 5: # trying to assign inside if — illegal
print("five")
Error: SyntaxError: invalid syntax
# FIX: Use == (double equals) for comparison, = for assignment
if x == 5: # == means "is x equal to 5?"
print("five")
TypeError — Wrong Type for an Operation
# MISTAKE: Trying to do math with input() without converting
age = input("Enter age: ") # stores "20" as a STRING even if user types 20
result = age + 1 # cannot add string and integerError: TypeError: can only concatenate str (not "int") to str
# FIX: Convert input to integer first
age = int(input("Enter age: ")) # convert immediately when getting input
result = age + 1 # now works: number + numberNameError — Variable Used Before Being Created
# MISTAKE: Using a variable before creating it print(student_score) # student_score has never been assigned a value
Error: NameError: name 'student_score' is not defined
# FIX: Create the variable before using it student_score = 85 # create and assign first print(student_score) # now this works fine
IndentationError — Inconsistent Spacing
# MISTAKE: Missing indentation in a block
if True:
print("This should be indented") # ERROR: not indentedError: IndentationError: expected an indented block after 'if' statement
# FIX: Add 4 spaces (or 1 Tab) before code inside a block
if True:
print("This is correctly indented") # 4 spaces of indentation
ValueError — Right Type, Wrong Value
# MISTAKE: Converting non-numeric text to a number
age = int("twenty") # "twenty" is not a valid integer
Error: ValueError: invalid literal for int() with base 10: 'twenty'
# FIX: Check the input is numeric before converting
text = input("Enter age: ")
if text.isdigit(): # check if every character is a digit
age = int(text) # safe to convert
print("Age:", age)
else:
print("Please enter only numbers!") # inform the userZeroDivisionError — Dividing by Zero
# MISTAKE: Dividing by zero (impossible in math too) result = 10 / 0 # cannot divide by zero
Error: ZeroDivisionError: division by zero
# FIX: Check if the denominator is zero before dividing
denominator = int(input("Enter denominator: "))
if denominator != 0: # only divide if it is not zero
result = 10 / denominator
print("Result:", result)
else:
print("Error: Cannot divide by zero!")