Python If…Else
Python's conditionals are just if, elif, and else. Indentation marks each branch's body.
The shape
PYTHON
x = 7
if x > 10:
print('big')
elif x > 5:
print('mid')
else:
print('small')
Inline (ternary)
PYTHON
greeting = 'Hi' if friendly else 'Greetings' parity = 'even' if n % 2 == 0 else 'odd'
Truth tests
Every expression in an if is converted to bool. Use that:
PYTHON
if items: # better than: if len(items) > 0:
process(items)
if not name: # better than: if name == '':
name = 'anonymous'
Chained comparisons
PYTHON
if 18 <= age <= 65:
print('working age')
Common smells
| Bad | Better |
|---|---|
if x == True: | if x: |
if x == None: | if x is None: |
if len(s) > 0: | if s: |
Tip: Deeply nested
ifs hide bugs. Use early return or raise to flatten the happy path.Example
Example
x = 7
if x > 10:
print('big')
elif x > 5:
print('mid')
else:
print('small')
Try it Yourself »
Exercise
Second branch of an if-chain.
if x: ...
y: ...
else: ...
Four letters; same as else+if.
Discussion
Loading…