Sub topic 3
Python if, elif, and else Statements
Assume you can run Python scripts and know variables, basic types, print(), and functions. This chapter focuses on conditions that combine comparisons and control program flow.
Chained comparisons
Python lets you write a range test naturally:
x = 7
if 0 <= x < 10:
print("single digit")This means 0 <= x and x < 10. Python evaluates the shared middle value only once. Chained comparisons are clearer than repeating x.
Membership and identity
Use in to test whether a value occurs in a sequence or collection. Use is for object identity, especially when checking None.
| Test | Meaning |
|---|---|
| `name in names` | `name` is contained in `names` |
| `value is None` | `value` is the special missing-value object |
status = None
if status is None:
print("status was not provided")Do not use is to compare ordinary values. Use == for value equality.
Nested conditionals
A nested conditional places one decision inside another:
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("enter")
else:
print("buy a ticket")
else:
print("too young")Nesting can express dependent decisions, but several levels make the logic harder to trace.
Guard clauses
A guard clause handles an invalid or simple case immediately. In a function, return avoids deep nesting:
def shipping_cost(weight):
if weight <= 0:
raise ValueError("weight must be positive")
if weight <= 1:
return 5
if weight <= 5:
return 10
return 20Conditional expressions
For a simple two-way choice, use value_if_true if condition else value_if_false:
n = 4
label = "even" if n % 2 == 0 else "odd"
print(label)Do not use this form for several statements or complicated logic.
Common pitfalls
=assigns a value;==compares values.- Indent every statement belonging to a block after its colon.
- In an
elifchain, Python runs only the first true branch. - An empty collection,
0,False, andNoneare falsy. - Use
is None, not== None, for a missing value. andandorshort-circuit. Insettings and settings["debug"], the second expression is skipped whensettingsis empty.
When to use `match`
For Python 3.10 or later, match can make one-value comparisons clearer than a long elif chain:
def describe(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case _:
return "Other"Use elif for ranges or unrelated conditions. Use match when comparing one value with several fixed patterns.
Exercise
Which test correctly checks whether result is missing rather than equal to zero?
Show answer
if result is None: