Sub topic 14
Common pitfalls and how to avoid them
This chapter assumes you can write if, elif, and else blocks, know the comparison and logical operators, and understand truthiness. It covers the mistakes that cause most conditional bugs.
Using = instead of ==
= assigns a value. == compares two values. Python rejects assignment inside an if condition as a syntax error, so this mistake fails loudly.
age = 20
# if age = 18: # SyntaxError: invalid syntax
if age == 18:
print('exactly 18')
else:
print('not 18')The walrus operator := does assign inside a condition, but only when you write it on purpose.
Using is to compare values
== asks whether two values are equal. is asks whether two names point to the same object. Use is only for None, True, and False.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True: same contents
print(a is b) # False: two separate list objectsSmall integers and short strings are sometimes shared between names, so is may appear to work on them. That behavior is an implementation detail and you should not rely on it.
Treating zero, empty, and missing as the same
A truthiness test like if not count is true for 0, '', [], and None. When zero is a legitimate value, the test hides the difference.
def describe(count):
if count is None:
return 'missing'
if count == 0:
return 'zero'
return 'a number was provided'
print(describe(None))
print(describe(0))
print(describe(5))Use is None when you mean "no value was given". Use plain truthiness when empty and missing really do mean the same thing.
Writing a condition that is always true
This looks correct but does not work:
color = 'blue'
if color == 'red' or 'green':
print('warm or natural')Python reads this as (color == 'red') or 'green'. A non-empty string is truthy, so the condition is always true. Compare each value, or use in:
color = 'blue'
if color in ('red', 'green'):
print('red or green')
else:
print('something else')Putting elif branches in the wrong order
An elif chain runs the first branch whose condition is true. If a broad condition comes first, it hides the narrower ones after it.
score = 95
if score >= 70:
grade = 'C'
elif score >= 90:
grade = 'A' # never reached
else:
grade = 'F'
print(grade) # COrder conditions from most specific to least specific. Here, test >= 90 before >= 70.
Using separate ifs when you need a chain
Each if is tested on its own. A chain of if, elif, and else runs at most one block.
n = 15
if n % 3 == 0:
print('three')
if n % 5 == 0:
print('five')
if n % 3 == 0:
print('chain: three')
elif n % 5 == 0:
print('chain: five')The first pair prints both lines. The chain prints only chain: three. Choose the form that matches the logic you want.
Mixing tabs and spaces
Python 3 raises a TabError when indentation mixes tabs and spaces ambiguously. Configure your editor to insert four spaces when you press Tab.
Quick reference
| Pitfall | Symptom | Fix |
|---|---|---|
| `=` in a condition | SyntaxError | Use `==` |
| `is` on values | Wrong result for equal values | Use `==`; keep `is` for `None` |
| `if not x` with 0 | Zero treated as missing | Use `x is None` |
| `x == 'a' or 'b'` | Always true | Use `x in ('a', 'b')` |
| Broad `elif` first | Later branches never run | Order specific to general |
| Several `if`s | More than one block runs | Use `elif` |
Exercise
What does this code print, and why? Fix it so it prints 'no'. answer = 'no' if answer == 'yes' or 'y': print('yes') else: print('no')
Show answer
It prints 'yes', because the condition is read as (answer == 'yes') or 'y', and the non-empty string 'y' is always truthy. Fix it with if answer in ('yes', 'y'):, which is false for 'no', so the else branch prints 'no'.
Exercise
A function receives retries, where 0 is a valid setting and None means "not configured". Which test should check for "not configured", if not retries or if retries is None?
Show answer
Use if retries is None. The test if not retries is also true when retries is 0, so it would wrongly treat a valid setting as missing.