Python course / Foundations
Conditions and branching
Make a program choose, with if, elif and match, and combine conditions without tying them in knots. The traps here are quiet ones: floats that do not compare as you expect, an or that looks right and is not, None mistaken for zero.
- comparisons
- if and elif
- and, or, not
- truthiness
- None vs falsy
- match
- nesting
- walrus
Runs in your browser. Start straight away; create an account when you want your progress kept.
def fare(age, day):
if age < 5:
return 0.0
if age < 16 or age >= 65:
return 1.20
if day in ("Saturday", "Sunday"):
return 1.80
return 2.40
for case in [(3, "Monday"), (12, "Monday"), (30, "Sunday"), (30, "Monday")]:
print(case, "->", fare(*case))
(3, 'Monday') -> 0.0 (12, 'Monday') -> 1.2 (30, 'Sunday') -> 1.8 (30, 'Monday') -> 2.4
What you will learn
- Run code only when a condition holds.
- Pick one outcome from several, in the right order.
- Combine conditions and control how they group.
- Tell a missing value from a falsy one, and is from ==.
- Choose a branch by comparing one value against several patterns.
- Turn deep nesting into a flat chain, in an order that is safe.
The lessons in this module
- Comparisons
- Comparing text and numbers
- if
- else
- elif
- Comparing decimals
- and, or, not
- Truthiness
- Empty collections
- The or trap
- None, == and is
- Chained comparisons
- in
- not in
- Conditional expressions
- match
- The capture trap
- Matching shapes
- Nested conditions
- Flattening nested conditions
- Assigning inside a condition
- Module review: ticket desk
Ready when you are
Previous: Values and variables. Next: Loops. All modules are on the course page.