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
- x
- —
- test
- —
- total
- 0
total is bound to 0
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 += xTwo 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 items does iterations; a loop nested inside another is 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
From the assignment paper
Modeled on NITJ AI-503, Assignment/Quiz
0 / 5 answered
Where next: the built-in containers — lists, tuples, sets and dicts — that loops iterate over and that hold a program's data.