Sub topic 14
Common pitfalls and how to avoid them
This chapter assumes you can write if, elif, and else blocks, and that you know truthiness, and/or/not, and in and is from earlier chapters. It collects the mistakes that most often cause wrong branches or confusing errors. For each one it shows the symptom, the cause, and the fix.
Pitfall 1: `=` instead of `==`
= assigns a value. == compares two values. Python rejects an assignment used as a condition.
age = 20
# if age = 18: # SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
if age == 18:
print('exactly 18')
else:
print('not 18')Python reports this as a syntax error, so the mistake is easy to catch. The walrus operator := does assign inside a condition, but only when you write it deliberately:
data = [3, 4, 5]
if (n := len(data)) > 2:
print(f'{n} items')Pitfall 2: comparing with `is` instead of `==`
== asks whether two values are equal. is asks whether two names refer to the same object. Using is for numbers or strings can work by accident and then fail.
a = 1000
b = 500 + 500
print(a == b) # True
print(a is b) # Often False; the result depends on the implementationPython caches some small integers and some strings, so is may return True for them. You cannot rely on that. Use is only for singletons: None, True, and False. For everything else, use ==.
value = None
if value is None:
print('missing')Recent Python versions emit a SyntaxWarning when you write x is 'text' or x is 5, because this is almost always a bug.
Pitfall 3: testing truthiness when you mean `None`
An if not x: test treats 0, 0.0, '', [], {}, set(), False, and None the same. If 0 or an empty string is a legitimate value, this test gives the wrong answer.
def describe_discount(discount=None):
if not discount:
return 'no discount given'
return f'{discount}% off'
print(describe_discount(0)) # no discount given (wrong: 0 was given)
print(describe_discount(None)) # no discount givenThe fix is to test for exactly the case you mean:
def describe_discount(discount=None):
if discount is None:
return 'no discount given'
return f'{discount}% off'
print(describe_discount(0)) # 0% off
print(describe_discount(None)) # no discount givenUse plain truthiness when you really mean "anything empty or zero". Use is None when you mean "nothing was provided".
Pitfall 4: `x == 1 or 2`
Python reads x == 1 or 2 as (x == 1) or 2. The number 2 is truthy, so the whole condition is always truthy.
color = 'green'
if color == 'red' or 'blue':
print('primary color') # runs for every value of colorWrite each comparison in full, or use in:
color = 'green'
if color == 'red' or color == 'blue':
print('primary color')
if color in ('red', 'blue'):
print('primary color')The in form is shorter and scales to longer lists of values.
Pitfall 5: `not` and `in`/`is` precedence
not binds more loosely than comparisons, so not x == 3 means not (x == 3). This works, but there are cleaner spellings for membership and identity:
names = ['ana', 'bo']
name = 'cy'
if not name in names: # works, but reads awkwardly
print('unknown')
if name not in names: # preferred
print('unknown')
thing = 5
if thing is not None: # preferred over: not thing is None
print('has a value')Precedence also matters when you mix and and or. and binds tighter than or:
age = 70
member = False
student = False
# Parsed as: age < 18 or (member and student)
if age < 18 or member and student:
print('discount')
else:
print('full price')If you want (age < 18 or member) and student, add the parentheses. Even when the default parse is the one you want, parentheses help the next reader.
Pitfall 6: a chain of `if` where you need `elif`
Separate if statements are independent. Every one of them is tested. An elif chain stops at the first match.
score = 95
if score >= 90:
print('A')
if score >= 80:
print('B')
if score >= 70:
print('C')This prints A, B, and C. Change the second and third if to elif and it prints only A.
The reverse mistake also happens. If you want several independent checks, such as validating each field of a form, separate if statements are correct.
Pitfall 7: wrong order in an `elif` chain
Because the first true branch wins, order matters when conditions overlap. Put the most specific test first.
score = 95
if score >= 70:
grade = 'C'
elif score >= 80:
grade = 'B'
elif score >= 90:
grade = 'A'
else:
grade = 'F'
print(grade) # C, which is wrongThe first test already matches 95, so the later branches never run. Order the tests from the strictest threshold to the loosest, as in the grade example from the elif chapter.
Pitfall 8: indentation errors
Python uses indentation to define blocks. Three errors are common:
- A missing indented block after the colon raises
IndentationError: expected an indented block. - Mixing tabs and spaces raises
TabError. Configure your editor to insert four spaces. - Wrong indentation of a line that should be inside or outside the block changes the meaning without any error.
total = 0
prices = [5, 10]
for price in prices:
if price > 5:
total += price
print('checked') # runs for every price, inside the loop but outside the if
print(total)If a statement should run only when the condition is true, it must be indented under the if. Also remember the colon. Forgetting it after if, elif, or else is a SyntaxError.
Pitfall 9: floating-point equality
Floating-point numbers store approximations, so == can fail for values that look equal.
import math
total = 0.1 + 0.2
if total == 0.3:
print('equal')
else:
print('not equal') # this runs
if math.isclose(total, 0.3):
print('close enough') # this runsUse math.isclose for floats, or work in integers (such as cents) or decimal.Decimal when exactness matters.
Pitfall 10: evaluating the wrong thing first
Short-circuiting protects you only if the safe test comes first. and stops at the first falsy operand, and or stops at the first truthy one.
settings = {}
# Raises KeyError: 'debug' is evaluated when settings is empty? No: settings is falsy, so and stops.
if settings and settings['debug']:
print('debug on')
# Dangerous order: the key is read before the guard.
# if settings['debug'] and settings:A related problem is a condition with side effects, such as calling a function that modifies state. Short-circuiting can skip it, which makes the program behave differently depending on the values. Keep conditions free of side effects, and compute a result in a variable first when you need the call to happen.
For dictionaries, settings.get('debug') returns None for a missing key and avoids the KeyError entirely.
Pitfall 11: redundant comparisons to `True` and `False`
Writing if flag == True: is longer than if flag: and fails for truthy values that are not equal to True, such as 2 or a non-empty list.
flag = 2
if flag == True:
print('equal to True') # does not run
if flag:
print('truthy') # runsLikewise, return a condition directly instead of branching to return True or False:
def is_adult(age):
return age >= 18A checklist before you commit
| Question | What to check |
|---|---|
| Is it `==` or `is`? | Use `is` only with `None`, `True`, and `False`. |
| Could `0` or `''` be valid? | Use `is None` rather than `not x`. |
| Is there an `or` with a bare value? | Write `x == a or x == b`, or use `in`. |
| Are the conditions ordered correctly? | Test the most specific case first. |
| Should this be `elif`? | Use `elif` when exactly one branch may run. |
| Are floats compared exactly? | Use `math.isclose`. |
| Is the guard before the risky access? | Put the safe test on the left of `and`. |
Exercise
This function should return 'weekend' for 'sat' and 'sun', and 'weekday' for anything else, but it returns 'weekend' every time. Find the bug and fix it. def kind(day): if day == 'sat' or 'sun': return 'weekend' return 'weekday'
Show answer
The condition is parsed as (day == 'sat') or 'sun', and the non-empty string 'sun' is always truthy. Fix it with if day == 'sat' or day == 'sun': or, better, if day in ('sat', 'sun'):.
Exercise
A function receives an optional retries argument, where 0 is a valid value meaning "do not retry" and None means "use the default of 3". Why does retries = retries or 3 break this, and what should you write instead?
Show answer
0 is falsy, so retries or 3 replaces a deliberate 0 with 3. Write if retries is None: retries = 3, or retries = 3 if retries is None else retries.
Exercise
Why can if total == 0.3: fail when total = 0.1 + 0.2, and how do you compare the two safely?
Show answer
Floats are stored as binary approximations, so 0.1 + 0.2 is 0.30000000000000004, not exactly 0.3. Use math.isclose(total, 0.3), or use integers or decimal.Decimal when exact results are needed.