Wiki
Intro11 min read

Control flow: booleans, branches and loops

Truth values, if/elif/else, and the two loop forms that decide how many times a block runs.

A program that always runs the same statements is a calculator. The moment it can test a condition and choose, it becomes a program. Every branch and loop in Python rests on one small idea: some values are truthy, others are falsy, and if and while consult that property.

Two questions, two tools

A branch asks "should this run once?" and a loop asks "should this run again?". Both are driven by the same truth test. The familiar True and False are only two of many truthy and falsy values — 0, "", [] and None are all falsy too.

The stepper below executes one small loop. Every press advances a real execution record, so the highlighted line and the values always agree.

Step the loop and watch each branch decision

1total = 0
2for x in data:
3 if x % 2 == 1:
4 total += x
5 if break_early and total > 10:
6 break
31415926
x
—
test
—
total
0

total is bound to 0

1 / 18

The test is evaluated before the body every time, so the number of additions equals the number of odd values — not the length of the list. `break` is an early exit that ends the loop immediately, skipping the rest of the data entirely.

Watch the loop variable x move through the list once, and notice that total changes only on the odd values — the if filters, it does not stop.

Conditions are expressions

Any expression can stand where a condition is expected; Python calls bool() on it. Comparisons (==, <, >=) return True or False, and the boolean operators and, or and not combine them with short-circuit evaluation: and stops at the first falsy operand, or at the first truthy one. That is why if key in table and table[key] > 0: is safe — the second test never runs when the first fails.

Chained comparisons do what mathematicians write:

if 0 <= index < len(items):   # one comparison range, no and needed
    print(items[index])

Branches

if runs a block when its condition is truthy; elif chains mutually exclusive alternatives; else is the fallback. Python selects the first matching branch and skips the rest, so order matters when conditions overlap.

Order of elif clauses is a correctness decision

Put the specific cases before the general ones. If you test score >= 50 before score >= 90, the second can never run. The interpreter does not warn you; you simply get the wrong grade.

Loops

for iterates over the items of any iterable — a list, string, range, dict, file — binding the loop variable to each in turn. while repeats as long as a condition stays truthy, which is the right tool when you do not know the number of iterations in advance.

for x in [3, 1, 4, 1, 5]:
    if x % 2 == 1:
        total += x

Two keywords change the flow inside a loop. break exits immediately; continue skips to the next iteration. A loop may also carry an else clause, which runs only if the loop finished without hitting break — a neat way to express "searched the whole list and found nothing".

Complexity of a simple loop

A single loop over nn items does O(n)O(n) iterations; a loop nested inside another is O(n2)O(n^2) if both run over the same input. The body cost multiplies the iteration count, so the shape of the nesting, not the number of lines of code, is what you estimate.

Illustrative vs real

The stepper runs on a fixed short list so every step is visible. Real loops range over millions of items, and real programs often replace an explicit loop with a comprehension or a library call. The semantics — test first, body once per item, break exits — are identical either way.

Check yourself

Eduspheria wiki · Programming & Data Structures, Python foundations

0 / 5 answered

  1. 1Which value is falsy in Python?
    Multiple choice
  2. 2A for loop's else clause runs even if the loop was exited with break.
    True / false
  3. 3For n = 100, how many times does the body of a doubly nested loop run if both loops run n times?
    iterations
    Numeric answer
  4. 4Which keyword skips the rest of the current iteration and continues with the next one?
    Short answer
  5. 5Python lets you write a single chained comparison checking that i is at least 0 and less than the length of a. How is it evaluated?
    Multiple choice

From the assignment paper

Modeled on NITJ AI-503, Assignment/Quiz

0 / 5 answered

  1. 1A loop runs for i in range(100) and prints file.read(10) on each pass. If every read returns 10 characters, how many characters are printed in total?
    characters
    Numeric answer
  2. 2How many times does the body of for i in range(1, 6): run?
    times
    Numeric answer
  3. 3range(3) produces the values 1, 2 and 3.
    True / false
  4. 4Which loop keyword leaves the loop immediately without running the rest of the current pass?
    Short answer
  5. 5When the number of repetitions is not known in advance and depends on a condition, which loop form fits best?
    Multiple choice

Where next: the built-in containers — lists, tuples, sets and dicts — that loops iterate over and that hold a program's data.