Fundamentals 10 min read

Common Python Errors and How to Fix Them

This article presents 17 frequent Python runtime and syntax errors, explains why they occur, and provides clear code examples and corrections to help beginners quickly identify and resolve these issues while improving their debugging skills.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Common Python Errors and How to Fix Them

Beginners often encounter runtime and syntax errors when writing Python code; this guide lists 17 common mistakes, explains the resulting exceptions, and shows how to correct them.

1. Missing colon after statements (if, for, def, etc.) causes SyntaxError: invalid syntax . Example:

<code>if spam == 42
  print('Hello!')</code>

Fix: add a colon at the end of the statement.

2. Using assignment operator (=) instead of equality operator (==) also raises SyntaxError: invalid syntax . Example:

<code>if spam = 42:
    print('Hello!')</code>

Fix: replace = with == for comparisons.

3. Incorrect indentation leads to IndentationError: unexpected indent , IndentationError: unindent does not match any outer indentation level , or IndentationError: expected an indented block . Example:

<code>print('Hello!')
  print('Howdy!')</code>

Fix: ensure indentation only follows lines ending with a colon and matches previous block levels.

4. Forgetting to call len() in a for loop results in TypeError: 'list' object cannot be interpreted as an integer . Example:

<code>spam = ["cat", "dog", "mouse"]
for i in range(spam):
    print(spam[i])</code>

Fix: use range(len(spam)) or iterate directly over the list.

5. Trying to modify a string raises TypeError: 'str' object does not support item assignment . Example:

<code>spam = "I have a pet cat."
spam[13] = 'r'
print(spam)</code>

Fix: create a new string using slicing: <code>spam = "I have a pet cat." spam = spam[:13] + 'r' + spam[14:] print(spam)</code>

6. Concatenating non‑string values with strings triggers TypeError: Can't convert 'int' object to str implicitly . Example:

<code>numEggs = 12
print('I have ' + numEggs + ' eggs.')</code>

Fix: convert the integer to a string or use formatted output: <code>print('I have ' + str(numEggs) + ' eggs.') print('I have %s eggs.' % numEggs)</code>

7. Missing quotes around string literals causes SyntaxError: EOL while scanning string literal . Example:

<code>print(Hello!')
print('Hello!)
myName = 'Al'
print('My name is ' + myName + . How are you?')</code>

Fix: ensure all string literals are enclosed in matching quotes.

8. Misspelling variable or function names leads to NameError: name 'fooba' is not defined . Example:

<code>foobar = 'Al'
print('My name is ' + fooba)</code>

Fix: use the correct identifier spelling.

9. Misspelling method names raises AttributeError: 'str' object has no attribute 'lowerr' . Example:

<code>spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()</code>

Fix: use the correct method name, e.g., lower() .

10. Accessing a list index beyond its range triggers IndexError: list index out of range . Example:

<code>spam = ['cat', 'dog', 'mouse']
print(spam[6])</code>

Fix: ensure the index is within the list bounds.

11. Using a non‑existent dictionary key raises KeyError: 'spam' . Example:

<code>spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])</code>

Fix: check that the key exists or use dict.get() .

12. Using Python keywords as variable names results in SyntaxError: invalid syntax . Example:

<code>class = 'algebra'</code>

Fix: avoid reserved words; see the list of Python keywords.

13. Using the increment operator ( += ) on an uninitialized variable causes NameError: name 'foobar' is not defined . Example:

<code>spam = 0
spam += 42
eggs += 42</code>

Fix: initialize the variable before applying += .

14. Referencing a local variable before assignment when a global variable of the same name exists raises UnboundLocalError . Example:

<code>someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()</code>

Fix: declare the variable as global inside the function or avoid name clashes.

15. Trying to assign to a range() object yields TypeError: 'range' object does not support item assignment . Example:

<code>spam = range(10)
spam[4] = -1</code>

Fix: convert the range to a list first: spam = list(range(10)) .

16. Using ++ or -- operators causes SyntaxError: invalid syntax . Example:

<code>spam = 1
spam++</code>

Fix: use spam += 1 or spam = spam + 1 .

17. Forgetting to include self as the first parameter of a class method results in TypeError: myMethod() takes no arguments (1 given) . Example:

<code>class Foo():
    def myMethod():
        print('Hello!')
a = Foo()
a.myMethod()</code>

Fix: define the method as def myMethod(self): .

These examples illustrate typical pitfalls for new Python developers and provide concrete corrections to improve code reliability.

debuggingprogrammingRuntimeSyntaxerrors
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.