Common Python Errors and How to Fix Them
This article lists 17 common Python runtime and syntax errors that beginners often encounter, explains the cause of each error, and provides corrected code examples to help readers quickly identify and resolve these issues.
For beginners learning Python, encountering runtime and syntax errors is common; this guide compiles 17 typical errors, explains their causes, and shows corrected code examples.
1. Missing colon after statements such as if, for, def, elif, else, class
This omission triggers a SyntaxError: invalid syntax . Example of the error:
if spam == 42
print('Hello!')Correct code should include a colon:
if spam == 42:
print('Hello!')2. Using = instead of == for comparison
Assigning instead of comparing also raises SyntaxError: invalid syntax . Erroneous code:
if spam = 42:
print('Hello!')Correct code uses the equality operator:
if spam == 42:
print('Hello!')3. Incorrect indentation
Wrong indentation can cause IndentationError: unexpected indent , IndentationError: unindent does not match any outer indentation level , or IndentationError: expected an indented block . Example:
print('Hello!')
print('Howdy!')Fix by aligning indentation properly:
print('Hello!')
print('Howdy!')or, if the second line belongs to the if block:
if spam == 42:
print('Hello!')
print('Howdy!')4. Forgetting to call len() in a for loop
This leads to TypeError: 'list' object cannot be interpreted as an integer . Erroneous code:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])Correct code uses the length of the list:
spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
print(spam[i])5. Trying to modify a string
Strings are immutable, causing TypeError: 'str' object does not support item assignment . Erroneous code:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)Fix by creating a new string:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)6. Concatenating non‑string values with strings
This raises TypeError: Can't convert 'int' object to str implicitly . Erroneous code:
numEggs = 12
print('I have ' + numEggs + ' eggs.')Convert the number to a string first:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
# or using formatting
print('I have %s eggs.' % numEggs)7. Missing quotes around string literals
Results in SyntaxError: EOL while scanning string literal . Example:
print(Hello!')
print('Hello!)
myName = 'Al'
print('My name is ' + myName + . How are you?)Correct usage adds matching quotes:
print('Hello!')
print('Hello!')
myName = 'Al'
print('My name is ' + myName + '. How are you?')8. Misspelling variable or function names
Leads to NameError: name 'fooba' is not defined . Example:
foobar = 'Al'
print('My name is ' + fooba)
spam = round(4.2)
spam = Round(4.2)Fix by using the correct identifiers:
foobar = 'Al'
print('My name is ' + foobar)
spam = round(4.2)
spam = round(4.2)9. Misspelling method names
Causes AttributeError: 'str' object has no attribute 'lowerr' . Example:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()Use the correct method name:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lower()10. Indexing beyond the end of a list
Raises IndexError: list index out of range . Example:
spam = ['cat', 'dog', 'mouse']
print(spam[6])Ensure the index is within bounds:
spam = ['cat', 'dog', 'mouse']
print(spam[2]) # prints 'mouse'11. Accessing a non‑existent dictionary key
Triggers KeyError: 'spam' . Example:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])Check that the key exists or use dict.get() :
print('The name of my pet zebra is ' + spam.get('zebra', 'unknown'))12. Using a Python keyword as a variable name
Results in SyntaxError: invalid syntax . Example:
class = 'algebra'Choose a different identifier:
my_class = 'algebra'Python keywords include and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield.
13. Using an increment operator on a variable without an initial value
Leads to NameError: name 'foobar' is not defined . Example:
spam = 0
spam += 42
eggs += 42Initialize variables before using them:
spam = 0
spam += 42
eggs = 0
eggs += 4214. Referencing a local variable before it is assigned
Raises UnboundLocalError: local variable 'foobar' referenced before assignment . Example:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()Declare the variable as global or avoid using it before assignment:
someVar = 42
def myFunction():
global someVar
print(someVar)
someVar = 100
myFunction()15. Trying to assign to an element of a range object
Produces TypeError: 'range' object does not support item assignment . Example:
spam = range(10)
spam[4] = -1Convert the range to a list first:
spam = list(range(10))
spam[4] = -116. Using ++ or -- operators
Python does not support these and raises SyntaxError: invalid syntax . Example:
spam = 1
spam++Use augmented assignment instead:
spam = 1
spam += 117. Forgetting the self parameter in a class method
Leads to TypeError: myMethod() takes no arguments (1 given) . Example:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()Define the method with the self parameter:
class Foo():
def myMethod(self):
print('Hello!')
a = Foo()
a.myMethod()By understanding these common pitfalls and applying the corrected examples, Python beginners can more efficiently debug their code and develop better programming habits.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.