Skip to content
Streak:0Loading your progress…Sign in

Module 1 · Lesson 2 of 3

Control flow

if/elif/else, for-in loops, range(), while, and match. ~15 min

Lesson notes

Coming from TypeScript

TypeScript

for (let i = 0; i < 5; i++) {
  if (i % 2 === 0) console.log(i);
  else if (i === 3) console.log("three");
}

Python

for i in range(5):
    if i % 2 == 0:
        print(i)
    elif i == 3:
        print("three")

Python uses == (no ===), and/or/not instead of &&/||/!, and elif.

for always iterates over something. range(stop), range(start, stop), range(start, stop, step) produce numbers; enumerate(items) gives (index, item) pairs; zip(a, b) walks two sequences together.

Structural pattern matching (Python 3.10+) — like Dart 3 switch expressions
def describe(event):
    match event:
        case {"type": "click", "x": x, "y": y}:
            return f"click at {x},{y}"
        case {"type": "key", "key": k}:
            return f"key {k}"
        case _:
            return "unknown"

Practice

  1. 1. FizzBuzz, returned not printed

    easy10 XP

    Write fizzbuzz(n) returning a list of strings for 1..n inclusive: "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, otherwise the number as a string.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. Route commands with match

    medium25 XP

    Write handle(cmd) taking a list of words. Return "moving <dir>" for ["go", dir], "picked <item>" for ["take", item], "bye" for ["quit"], and "???" for anything else. Use match.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor