Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 03 / 16

Programming learning path

Control flow: conditionals & loops

if/elif/else, while and for loops, range, break/continue, loop else and structural pattern matching.

if, elif and else

Branching logic with if/elif/else, and the match/case alternative for shape-based branching.

An if block runs its body only when its condition is truthy; an optional chain of elif blocks is checked in order, and only the first one whose condition is true runs; an optional final else runs if none of the above did. Indentation, not braces, defines each block's boundaries, so consistent indentation is not a style preference — it is the syntax. Since Python 3.10, match/case offers a structural alternative for branching on the shape of a value rather than a chain of equality checks, useful once you have more than a few related conditions to compare against one value.

Key points

  • elif branches are checked in order; only the first true one runs
  • Indentation defines block boundaries — it is syntax, not style
  • match/case (3.10+) suits structural branching better than a long elif chain

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

A grading function using an elif chain, where order matters: highest threshold first.

Common pitfalls

  • Writing elif score >= 70 before elif score >= 80 would make the 80 branch unreachable
  • Using multiple separate if statements instead of elif runs every matching block, not just the first

Practice exercise

Write classify_bmi(bmi) returning "underweight", "normal", "overweight" or "obese" using the standard BMI thresholds 18.5, 25 and 30, with an elif chain in the correct order.

while loops

Repeating code while a condition holds, and why forgetting to update the condition causes an infinite loop.

A while condition: block repeats its body for as long as condition remains truthy, re-checking it before every iteration, including the very first. while is the right tool when the number of iterations is not known in advance — waiting for user input to satisfy some rule, or processing a queue until it is empty — whereas for is better once you are iterating over a known, finite sequence. A while loop needs a deliberate termination strategy unless it is intentionally long-running: the condition can eventually become false, or execution can leave through break, return, or an exception — while True: itself is a completely standard, intentional pattern for event loops, servers and retry logic, as long as one of those exits is actually reachable.

Key points

  • while re-checks its condition before every iteration, including the first
  • Use while when the iteration count is unknown ahead of time
  • The loop needs a deliberate way to end: the condition can turn false, or break/return/an exception can exit it

Code

attempts = 0
while attempts < 3:
    guess = input("Guess the number: ")
    if guess == "7":
        print("Correct!")
        break
    attempts += 1
else:
    print("Out of attempts")

A bounded while loop that tracks attempts, with break on success and a loop-else for exhaustion.

Common pitfalls

  • while True: with no break anywhere inside runs forever
  • Forgetting attempts += 1 here would make the loop run exactly forever, not three times

Practice exercise

Write a while loop that keeps asking the user for a positive number and only stops once they enter one, printing an error message for anything else.

for loops and range()

for iterates directly over values; range(), enumerate() and zip() cover the common cases for counts, indexes and parallel iteration.

Python's for item in iterable: asks the iterable for its items one by one — not over numeric indices — which is why there is rarely a need for a C-style counting loop. Lists and strings yield their elements in order; a dictionary yields its keys by default, so use .values() or .items() when you need values or key-value pairs. range(start, stop, step) supplies a lazy integer sequence when you actually need positions or a fixed repeat count. enumerate(iterable, start=...) gives an index together with each value. zip(a, b, ...) walks multiple iterables in parallel and yields tuples, stopping when the shortest input is exhausted by default; use zip(..., strict=True) when different lengths should be treated as an error rather than silently truncated.

Key points

  • Iterate over values directly; dictionaries yield keys unless you use .values() or .items()
  • range() is for numeric sequences, enumerate() adds an index, and zip() pairs parallel iterables
  • zip() truncates to the shortest iterable by default; strict=True detects mismatched lengths

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Combining zip() and enumerate() to iterate over two related sequences with a readable 1-based position.

Common pitfalls

  • for i in range(len(items)): items[i] is usually less readable than iterating values directly
  • zip() silently stops at the shortest input unless strict=True is used
  • range(5) produces 0, 1, 2, 3, 4 — the stop value itself is excluded

Practice exercise

Given equally-sized lists of test names and durations, use zip(..., strict=True) and enumerate(..., start=1) to print a numbered report without indexing the lists manually.

break, continue and the loop else clause

Exiting a loop early, skipping to the next iteration, and the rarely-used else that runs only if break never fired.

break immediately exits the innermost enclosing loop entirely, skipping any remaining iterations. continue skips the rest of the current iteration's body and jumps straight to the next one, without exiting the loop. Both for and while support an optional trailing else: block that runs only if the loop completed all its iterations without hitting a break — a natural fit for "search and report not-found" patterns, though many developers find an explicit flag variable clearer and use that instead.

Key points

  • break exits the loop entirely; continue skips to the next iteration
  • A loop's else clause runs only if the loop finished without a break
  • An explicit flag variable is often clearer than loop-else for readers unfamiliar with it

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

A classic use of for-else: the else only prints when no divisor caused a break, meaning the number is prime.

Common pitfalls

  • Confusing loop-else with if-else — it runs on non-break completion, not on any specific condition
  • continue inside a while loop skips the update step too if that step comes after it, risking an infinite loop

Practice exercise

Write a loop over a list of numbers that skips negative numbers with continue, stops entirely if it finds a number greater than 100 with break, and otherwise sums the valid numbers.

Structural pattern matching with match/case

match/case selects a branch by the shape and contents of data, including destructuring and guarded patterns.

match value: is Python's structural pattern-matching statement. It is more powerful than a traditional switch because a case can check both values and the shape of a sequence, mapping or object while binding parts of the matched value to names. Cases are tried from top to bottom and only the first matching case runs. case _: is the wildcard fallback. A guard such as case {"status": code} if code >= 500: adds an ordinary boolean condition after the structural pattern matched. Pattern matching is useful when data naturally has several distinct shapes — parsed messages, events, command records — but a simple two-branch boolean decision is usually still clearer as if/else.

Key points

  • match/case can match structure and values while binding matched parts to local names
  • Cases are evaluated top-to-bottom and only the first matching case executes
  • case _ is the wildcard fallback; an if guard can add an extra condition

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Matching dictionary shapes, binding fields to names, and using a guard for a more specific first case.

Common pitfalls

  • Putting a broad case before a more specific one can make the later case unreachable in practice
  • A bare name in a pattern normally captures a value; it does not compare against an existing variable of the same spelling
  • Using match/case for a simple true/false decision can be less readable than if/else

Practice exercise

Write classify(response) using match/case for tuples shaped like (status_code, payload): handle 200 with any payload, 404 with a resource name, any 5xx status via a guard, and a wildcard fallback.

Source registry

3 chapter references
The Python Tutorial

Baseline syntax, control flow, functions and module basics

Python Software Foundation · Official documentation
Source ↗
PEP 634 — Structural Pattern Matching: Specification

match/case semantics introduced in Python 3.10

Python Software Foundation · Official specification
Source ↗
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗