Top 17 Common Python Errors and How to Fix Them
This guide lists the most frequent Python runtime and syntax errors—such as missing colons, misuse of assignment operators, indentation mistakes, type mismatches, and name errors—explains why they occur, and provides corrected code examples to help beginners debug their programs effectively.
1) Missing colon after statements (SyntaxError)
Forgetting the trailing colon in if, elif, else, for, while, class, or def statements triggers SyntaxError: invalid syntax.
if spam == 42:
print('Hello!')2) Using = instead of == (SyntaxError)
Assigning with = where a comparison is intended also raises a syntax error.
if spam = 42:
print('Hello!')3) Incorrect indentation (IndentationError)
Indentation must follow a line that ends with a colon and must be consistent throughout the block.
if spam == 42:
print('Hello!')
else:
print('Howdy!')4) Forgetting len() in a for loop (TypeError)
Iterating over a list or string directly with for i in spam works, but using range(spam) without len() causes TypeError: 'list' object cannot be interpreted as an integer.
spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
print(spam[i])5) Trying to modify a string (TypeError)
Strings are immutable; attempting item assignment raises TypeError: 'str' object does not support item assignment. Use slicing to create a new string.
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)6) Concatenating non‑string values with strings (TypeError)
Convert non‑string objects to strings before concatenation.
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')7) Missing quotes around string literals (SyntaxError)
Omitting opening or closing quotes leads to SyntaxError: EOL while scanning string literal.
print('Hello!') # correct
print('Hello!) # missing closing quote8) Misspelled variable or function names (NameError)
A typo in an identifier results in NameError: name 'foobar' is not defined.
foobar = 'Al'
print('My name is ' + fooba) # typo: fooba9) Misspelled method name (AttributeError)
Calling a non‑existent method such as lowerr() on a string raises AttributeError: 'str' object has no attribute 'lowerr'.
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr() # typo, should be lower()10) List index out of range (IndexError)
Accessing an index beyond the list length triggers IndexError: list index out of range.
spam = ['cat', 'dog', 'mouse']
print(spam[6]) # invalid index11) Missing dictionary key (KeyError)
Referencing a key that does not exist in a dictionary raises KeyError: 'spam'.
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])12) Using a Python keyword as a variable name (SyntaxError)
Keywords such as class, def, if, etc., cannot be used as identifiers.
class = 'algebra' # invalid13) Using augmented assignment without an initial value (NameError)
Before using +=, the variable must be defined.
spam = 0
spam += 42 # now valid14) Referencing a local variable before assignment (UnboundLocalError)
If a variable is assigned anywhere in a function, Python treats it as local throughout that function.
someVar = 42
def myFunction():
print(someVar) # UnboundLocalError because someVar is later assigned locally
someVar = 10015) Modifying a range object (TypeError)
range()returns an immutable range object in Python 3. Convert it to a list first if you need to assign items.
# Incorrect
spam = range(10)
spam[4] = -1
# Correct
spam = list(range(10))
spam[4] = -116) Using ++ or -- operators (SyntaxError)
Python does not support the increment/decrement operators found in C‑style languages.
# Incorrect
spam = 1
spam++
# Correct
spam = 1
spam += 117) Forgetting the self parameter in a method (TypeError)
Instance methods must declare self as the first parameter.
class Foo:
def myMethod(self):
print('Hello!')
a = Foo()
a.myMethod()These examples cover the most common pitfalls for beginners learning Python, helping them understand the cause of each error and how to correct their code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
