LevelJar Sign in

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

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

one value, several outcomes, in order
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

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

Start this module

Previous: Values and variables. Next: Loops. All modules are on the course page.