Matheion

MA-PY1 · Module 1.3

Branches and while loops

Topics: Conditionals · While loops

Overview

Module 1.3 — Branches and while loops

Scroll Core ideas → worked snippets → Practice (quiz). Attempt each question before Discuss / reveal. Use any Python REPL, script, or notebook you like.

Concepts

Core ideas — decisions and repetition with while

Programs need to branch (do one thing or another) and iterate (repeat while a condition holds). Python’s control flow is intentionally readable: keywords state intent, indentation shows structure.

Truthiness and conditions

Every value can be interpreted in a Boolean context:

  • Falsy: 0, 0.0, None, empty collections ('', [], {}, set()), and False.
  • Truthy: everything else (including "0"—it is a non-empty string).

if cond: runs its block when cond is truthy. Prefer explicit comparisons for numbers (n == 0) when zero vs missing could differ in later data types.

Logical operators short-circuit:

  • a and b evaluates b only if a is truthy.
  • a or b evaluates b only if a is falsy.
  • not x flips the truth value.

if / elif / else

Python walks from top to bottom and executes the first whose condition is true; else attaches to the whole chain. There is no “switch” keyword—long chains of discrete values often use if/elif, a dict of callables, or (later) match/case.

Keep branches shallow: guard clauses (early return inside a function) flatten logic:

def price(age):
    if age < 0:
        raise ValueError("age")
    if age < 18:
        return 5.0
    return 10.0

The line raise ValueError("age") is a first taste of error signalling: when an input makes no sense (a negative age), the function stops immediately and reports the problem instead of returning a misleading price. Read it for now as "halt here with a complaint." A later module is devoted entirely to raising and catching errors, so you do not need the full story yet — just recognise that raise aborts the current call on purpose.

while loops

Syntax: while condition: → body → re-check condition.

You are responsible for progress: some variable or external state must eventually make condition false. Common patterns:

  • Counter: i = 0 … i += 1 … while i < n.
  • Sentinel loop: read until a special value appears.
  • Drain a condition: your earlier Collatz-style “strip factors while divisible”.

Infinite loops are legal (while True: with break)—use when the exit check naturally sits mid-body.

break and continue

  • break: exit the innermost while/for immediately.
  • continue: skip the rest of this iteration; jump to the next condition test.

Overuse harms readability—sometimes an if/else inside the loop reads clearer.

Chained comparisons — Pythonic and safe

a < b <= c means (a < b) and (b <= c) with b evaluated once. That matters if b were an expensive expression (rare in intro code) and reads like mathematics.

Self-study checklist

  • For a given while, name the variant (what decreases or moves toward termination).
  • Translate one nested if into guarded early returns.
  • Predict 0 or 7 and 0 and 7 before using the REPL.

Examples

Worked snippets — branches and while

Simple if / elif / else

def letter_grade(score):
    if score < 0 or score > 100:
        raise ValueError("score out of range")
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 70:
        return "C"
    return "D"

print(letter_grade(85))

Boolean short-circuit

name = ""
display = name or "guest"
print(display)

Avoid using and/or tricks for branching until if versions feel bulky—prefer clarity first.

while countdown

n = 5
while n > 0:
    print(n)
    n -= 1

Sentinel-style loop (stdin-style pattern without I/O detail)

Imagine reading values until -1:

values = [3, 1, 4, -1]
i = 0
running = []
while True:
    v = values[i]
    if v == -1:
        break
    running.append(v)
    i += 1
print(running)

In real code you’d for over an iterator—but this shows break placement.

continue skips one iteration

total = 0
k = 0
while k < 5:
    k += 1
    if k % 2 == 0:
        continue
    total += k
print(total)  # 1 + 3 + 5 == 9

Stripping trailing factors (while + progress)

Repeatedly divide while still divisible—invariant: each step removes factors of 2:

def strip_twos(n):
    while n % 2 == 0:
        n = n // 2
    return n

print(strip_twos(40))  # → 5

Chained comparisons

x = 15
print(10 < x < 20)

Equivalent to x > 10 and x < 20 with x read once.

Practice check — branches and while loops

Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.

  1. 1.Consider: ```python score = 82 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F' ``` What is `grade`?

  2. 2.How many times does the body run? ```python n = 5 while n > 0: n = n - 2 ```

  3. 3.The chained comparison `1 < x < 10` is equivalent to which expression?

  4. 4.Inside a loop, what does `continue` do?

  5. 5.Which of these values is considered **falsy** (treated like `False` in a condition)?