COMMON PYTHON FIXES

Solve a Python Problem

Search a symptom, inspect broken code, and follow a full guide or a quick answer. Each guide explains the failure, its cause, the fix, and how to verify it.

47 results

Logic & loopsFULL GUIDE · 6 MIN READ

How to Fix ZeroDivisionError in Python

Dividing by zero stops a calculation. Trace where the divisor came from, decide what zero means for your program, and test that rule instead of hiding the error.

Basics & inputFrom Python History

Assuming the name means snake

The code runs, but the historical claim is false.

See the fix
COMMON MISTAKE
print("Python was named after a snake.")
FIX
print("Python was named after Monty Python.")

A program can run successfully and still print incorrect information. Check the fact as well as the syntax.

Basics & inputFrom Python History

Mixing up 1991 and 2008

The code runs, but it confuses two milestones.

See the fix
COMMON MISTAKE
print("Python 3.0 was first shared in 1991.")
FIX
print("Python was public in 1991; Python 3.0 arrived in 2008.")

Python's first public sharing and the Python 3.0 release happened at different times.

Basics & inputFrom Hello, World!

Unquoted text

NameError: Python looks for a variable named Hello.

See the fix
COMMON MISTAKE
print(Hello)
FIX
print("Hello")

Put literal text inside quotes so Python treats it as a string.

Basics & inputFrom Hello, World!

Missing parentheses

SyntaxError in Python 3.

See the fix
COMMON MISTAKE
print "Hello"
FIX
print("Hello")

print is a function, so its argument goes inside parentheses.

Basics & inputFrom Variables and Types

Case-sensitive names

NameError because Name and name are different names.

See the fix
COMMON MISTAKE
name = "Maya"
print(Name)
FIX
name = "Maya"
print(name)

Use exactly the same spelling and capitalization each time.

Basics & inputFrom Variables and Types

Mixing text and numbers

TypeError when joining a string and an integer.

See the fix
COMMON MISTAKE
age = 12
print("Age: " + age)
FIX
age = 12
print("Age: " + str(age))

Convert the number to a string before concatenating it with text.

CollectionsFrom Lists

Index past the end

IndexError because the only valid positive indexes are 0 and 1.

See the fix
COMMON MISTAKE
items = ["a", "b"]
print(items[2])
FIX
items = ["a", "b"]
print(items[1])

The final positive index is len(items) - 1.

CollectionsFrom Lists

Saving append's return value

The variable becomes None.

See the fix
COMMON MISTAKE
items = [1, 2]
items = items.append(3)
print(items)
FIX
items = [1, 2]
items.append(3)
print(items)

Call append without assigning its return value.

Logic & loopsFrom Basic Operators

Using ^ for powers

It prints 1 because ^ is bitwise XOR.

See the fix
COMMON MISTAKE
print(2 ^ 3)
FIX
print(2 ** 3)

Python's exponentiation operator is **.

Strings & textFrom String Formatting

Missing f prefix

The literal text Hi, {name} is displayed.

See the fix
COMMON MISTAKE
name = "Maya"
print("Hi, {name}")
FIX
name = "Maya"
print(f"Hi, {name}")

Add f before the opening quote to evaluate placeholders.

Strings & textFrom String Formatting

Unknown placeholder

NameError because username has not been defined.

See the fix
COMMON MISTAKE
name = "Maya"
print(f"Hi, {username}")
FIX
name = "Maya"
print(f"Hi, {name}")

A placeholder must refer to a defined name or valid expression.

Strings & textFrom Basic String Operations

Index outside a string

IndexError because valid positive indexes are 0, 1, and 2.

See the fix
COMMON MISTAKE
word = "cat"
print(word[3])
FIX
word = "cat"
print(word[2])

The last positive index is one less than the string length.

Strings & textFrom Basic String Operations

Changing a character in place

TypeError because strings cannot be changed in place.

See the fix
COMMON MISTAKE
word = "cat"
word[0] = "b"
FIX
word = "cat"
word = "b" + word[1:]
print(word)

Construct a new string and assign it to the variable.

Logic & loopsFrom Conditions

Missing colon

SyntaxError on the if line.

See the fix
COMMON MISTAKE
score = 75
if score >= 60
    print("Passed")
FIX
score = 75
if score >= 60:
    print("Passed")

End the if header with a colon.

Logic & loopsFrom Conditions

Missing indentation

IndentationError after the if header.

See the fix
COMMON MISTAKE
score = 75
if score >= 60:
print("Passed")
FIX
score = 75
if score >= 60:
    print("Passed")

Indent statements that belong to the branch.

Logic & loopsFrom Loops

A while loop never progresses

The condition stays true, so the loop keeps printing 0.

See the fix
COMMON MISTAKE
count = 0
while count < 3:
    print(count)
FIX
count = 0
while count < 3:
    print(count)
    count += 1

Update the value tested by the condition.

Logic & loopsFrom Loops

Expecting the stop value

Only 1, 2, and 3 appear.

See the fix
COMMON MISTAKE
for n in range(1, 4):
    print(n)
# Expecting 1, 2, 3, 4
FIX
for n in range(1, 5):
    print(n)

range excludes its stop argument.

Functions & classesFrom Functions

Printing instead of returning

The function prints 8, but result is None.

See the fix
COMMON MISTAKE
def double(value):
    print(value * 2)
result = double(4)
print(result)
FIX
def double(value):
    return value * 2
result = double(4)
print(result)

Use return when callers need to store or reuse the calculated value.

Functions & classesFrom Functions

Missing required argument

TypeError because name was not supplied.

See the fix
COMMON MISTAKE
def greet(name):
    print(f"Hi, {name}")
greet()
FIX
def greet(name):
    print(f"Hi, {name}")
greet("Maya")

Provide one argument for each required parameter.

Functions & classesFrom Classes and Objects

Omitting self in a method

TypeError because Python passes the instance automatically.

See the fix
COMMON MISTAKE
class Book:
    def summary():
        return "A book"
book = Book()
print(book.summary())
FIX
class Book:
    def summary(self):
        return "A book"
book = Book()
print(book.summary())

Instance methods need self as their first parameter.

Functions & classesFrom Classes and Objects

Forgetting self on an attribute

AttributeError because no title attribute was stored on the object.

See the fix
COMMON MISTAKE
class Book:
    def __init__(self, title):
        title = title
book = Book("Python Notes")
print(book.title)
FIX
class Book:
    def __init__(self, title):
        self.title = title
book = Book("Python Notes")
print(book.title)

Assign to self.title to save the value on the instance.

CollectionsFrom Dictionaries

Looking up a missing key

KeyError for score.

See the fix
COMMON MISTAKE
learner = {"name": "Maya"}
print(learner["score"])
FIX
learner = {"name": "Maya"}
print(learner.get("score", 0))

Use get with a fallback if the key may be absent.

CollectionsFrom Dictionaries

Using a list-style index

KeyError because 0 is not a key.

See the fix
COMMON MISTAKE
learner = {"name": "Maya"}
print(learner[0])
FIX
learner = {"name": "Maya"}
print(learner["name"])

Dictionary lookup uses keys, not numeric positions.

Files & setupFrom Modules and Packages

Using a module before importing it

NameError if math has not been imported in this run.

See the fix
COMMON MISTAKE
print(math.sqrt(9))
FIX
import math
print(math.sqrt(9))

Import the module before using its name.

Files & setupFrom Modules and Packages

Shadowing the module name

AttributeError because math now refers to the integer 4.

See the fix
COMMON MISTAKE
import math
math = 4
print(math.sqrt(9))
FIX
import math
number = 4
print(math.sqrt(9))

Avoid reusing an imported module's name for another value.

Basics & inputFrom Input and Output

Adding a number to input text

TypeError because entered_age is text.

See the fix
COMMON MISTAKE
entered_age = "17"
print(entered_age + 1)
FIX
entered_age = "17"
print(int(entered_age) + 1)

Convert numeric text before arithmetic.

Basics & inputFrom Input and Output

Converting nonnumeric text

ValueError because the text is not a valid integer.

See the fix
COMMON MISTAKE
entered_age = "seventeen"
print(int(entered_age))
FIX
entered_age = "17"
print(int(entered_age))

int accepts text that represents a valid whole number.

ProjectsFrom Project: Tip Calculator

Using the percent as a multiplier

A 20% tip on 40 becomes 800 instead of 8.

See the fix
COMMON MISTAKE
tip = bill * 20
FIX
tip = bill * 20 / 100

Convert a percent to a fraction before multiplying.

ProjectsFrom Project: Tip Calculator

Dividing before adding the tip

The whole tip is charged to every person.

See the fix
COMMON MISTAKE
each = bill / people + tip
FIX
each = (bill + tip) / people

Add the tip once to the whole bill, then split the total.

ProjectsFrom Project: Number Guessing Game

Assigning instead of comparing

SyntaxError because = is assignment, not comparison.

See the fix
COMMON MISTAKE
if guess = secret:
    print('Correct')
FIX
if guess == secret:
    print('Correct')

Use == when asking whether two values are equal.

ProjectsFrom Project: Number Guessing Game

Reversing the low hint

The player receives a misleading hint.

See the fix
COMMON MISTAKE
if guess < secret:
    return 'Too high'
FIX
if guess < secret:
    return 'Too low'

Compare the guessed number to the secret from the player's perspective.

ProjectsFrom Project: Text Analyzer

Counting the text's characters

'red blue' reports eight characters instead of two words.

See the fix
COMMON MISTAKE
word_count = len(text)
FIX
word_count = len(text.split())

Split the text first when you want a word count.

ProjectsFrom Project: Text Analyzer

Treating capitalization as a new word

'Code' and 'code' become separate dictionary keys.

See the fix
COMMON MISTAKE
words = text.split()
FIX
words = text.lower().split()

Normalize case before counting for a case-insensitive report.

CollectionsFrom Tuples and Sets

Expecting a set to preserve duplicates

It prints False because a set has only two distinct values.

See the fix
COMMON MISTAKE
print(len(set([1, 1, 2])) == 3)
FIX
print(len(set([1, 1, 2])) == 2)

A set keeps one copy of each equal value.

CollectionsFrom Tuples and Sets

Using {} for an empty set

AttributeError: a dictionary has no add method.

See the fix
COMMON MISTAKE
items = {}
items.add('python')
FIX
items = set()
items.add('python')

Construct an empty set with set().

Files & setupFrom Exceptions

Catching the wrong exception

ZeroDivisionError still stops the program.

See the fix
COMMON MISTAKE
try:
    print(4 / 0)
except ValueError:
    print('Bad number')
FIX
try:
    print(4 / 0)
except ZeroDivisionError:
    print('Cannot divide by zero')

The except type must match the error that may be raised.

Files & setupFrom Exceptions

Using a bare except

Unrelated bugs are hidden behind a vague message.

See the fix
COMMON MISTAKE
try:
    risky_code()
except:
    print('Something failed')
FIX
try:
    number = float('bad')
except ValueError:
    print('Invalid number')

Catch an expected error by name so other failures remain visible.

Files & setupFrom Reading and Writing Files

Reading before writing

FileNotFoundError if the virtual file has not been created in this run.

See the fix
COMMON MISTAKE
with open('new_note.txt', 'r', encoding='utf-8') as file:
    print(file.read())
FIX
with open('new_note.txt', 'w', encoding='utf-8') as file:
    file.write('Ready')
with open('new_note.txt', 'r', encoding='utf-8') as file:
    print(file.read())

Create the file before trying to read it in a fresh exercise run.

Files & setupFrom Reading and Writing Files

Expecting append from write mode

The old file contents disappear.

See the fix
COMMON MISTAKE
with open('note.txt', 'w', encoding='utf-8') as file:
    file.write('second')
FIX
with open('note.txt', 'a', encoding='utf-8') as file:
    file.write('second')

Choose a only when the new text should be added at the end.

Files & setupFrom Installing Python and Virtual Environments

Typing a terminal command into Python code

SyntaxError in the browser editor: this is a shell command.

See the fix
COMMON MISTAKE
python -m venv .venv
FIX
import sys
print(sys.version_info.major)

Use the browser editor for Python statements and a local terminal for setup commands.

Files & setupFrom Installing Python and Virtual Environments

Assuming a browser version is the local version

The claim may be false because the browser runtime is separate.

See the fix
COMMON MISTAKE
print('My laptop uses Python 3.13')
FIX
import sys
print(sys.version_info.major, sys.version_info.minor)

Inspect each interpreter in its own environment rather than assuming they match.

CollectionsFrom List Comprehensions

Filtering odd values by accident

The result contains doubled odd values, such as [2, 6] for [1, 2, 3, 4].

See the fix
COMMON MISTAKE
[n * 2 for n in numbers if n % 2]
FIX
[n * 2 for n in numbers if n % 2 == 0]

The remainder is 1 for odd numbers, which is truthy. Compare explicitly with zero for even values.

CollectionsFrom List Comprehensions

Putting the filter before the loop

SyntaxError: expected else after the conditional expression.

See the fix
COMMON MISTAKE
[n * 2 if n % 2 == 0 for n in numbers]
FIX
[n * 2 for n in numbers if n % 2 == 0]

A trailing if filters items. An if before for is a different expression form and needs an else branch.