No matches yet. Try another term or topic.
Basics & inputFrom Python History
Assuming the name means snake
The code runs, but the historical claim is false.
See the fix
COMMON MISTAKEprint("Python was named after a snake.")
FIXprint("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 MISTAKEprint("Python 3.0 was first shared in 1991.")
FIXprint("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 MISTAKEprint(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 MISTAKEprint "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 MISTAKEname = "Maya"
print(Name)
FIXname = "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 MISTAKEage = 12
print("Age: " + age)
FIXage = 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 MISTAKEitems = ["a", "b"]
print(items[2])
FIXitems = ["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 MISTAKEitems = [1, 2]
items = items.append(3)
print(items)
FIXitems = [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 MISTAKEprint(2 ^ 3)
Python's exponentiation operator is **.
Logic & loopsFrom Basic Operators
Dividing by zero
ZeroDivisionError.
See the fix
COMMON MISTAKEprint(10 / 0)
The divisor must be nonzero.
Strings & textFrom String Formatting
Missing f prefix
The literal text Hi, {name} is displayed.
See the fix
COMMON MISTAKEname = "Maya"
print("Hi, {name}")
FIXname = "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 MISTAKEname = "Maya"
print(f"Hi, {username}")
FIXname = "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 MISTAKEword = "cat"
print(word[3])
FIXword = "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 MISTAKEword = "cat"
word[0] = "b"
FIXword = "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 MISTAKEscore = 75
if score >= 60
print("Passed")
FIXscore = 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 MISTAKEscore = 75
if score >= 60:
print("Passed")
FIXscore = 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 MISTAKEcount = 0
while count < 3:
print(count)
FIXcount = 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 MISTAKEfor n in range(1, 4):
print(n)
# Expecting 1, 2, 3, 4
FIXfor 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 MISTAKEdef double(value):
print(value * 2)
result = double(4)
print(result)
FIXdef 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 MISTAKEdef greet(name):
print(f"Hi, {name}")
greet()
FIXdef 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 MISTAKEclass Book:
def summary():
return "A book"
book = Book()
print(book.summary())
FIXclass 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 MISTAKEclass Book:
def __init__(self, title):
title = title
book = Book("Python Notes")
print(book.title)
FIXclass 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 MISTAKElearner = {"name": "Maya"}
print(learner["score"])
FIXlearner = {"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 MISTAKElearner = {"name": "Maya"}
print(learner[0])
FIXlearner = {"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 MISTAKEprint(math.sqrt(9))
FIXimport 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 MISTAKEimport math
math = 4
print(math.sqrt(9))
FIXimport 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 MISTAKEentered_age = "17"
print(entered_age + 1)
FIXentered_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 MISTAKEentered_age = "seventeen"
print(int(entered_age))
FIXentered_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 MISTAKEtip = bill * 20
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 MISTAKEeach = bill / people + tip
FIXeach = (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 MISTAKEif guess = secret:
print('Correct')
FIXif 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 MISTAKEif guess < secret:
return 'Too high'
FIXif 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 MISTAKEword_count = len(text)
FIXword_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 MISTAKEwords = text.split()
FIXwords = 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 MISTAKEprint(len(set([1, 1, 2])) == 3)
FIXprint(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 MISTAKEitems = {}
items.add('python')
FIXitems = 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 MISTAKEtry:
print(4 / 0)
except ValueError:
print('Bad number')
FIXtry:
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 MISTAKEtry:
risky_code()
except:
print('Something failed')
FIXtry:
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 MISTAKEwith open('new_note.txt', 'r', encoding='utf-8') as file:
print(file.read())
FIXwith 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 MISTAKEwith open('note.txt', 'w', encoding='utf-8') as file:
file.write('second')
FIXwith 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 MISTAKEpython -m venv .venv
FIXimport 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 MISTAKEprint('My laptop uses Python 3.13')
FIXimport sys
print(sys.version_info.major, sys.version_info.minor)
Inspect each interpreter in its own environment rather than assuming they match.