Python Control Flow and Loops: if, for, while and Worked Traces

Learn to trace Python branches and loops without skipping a state change. Worked examples cover GCD, break and continue, loop else, nested loops, and common mistakes.

KnowledgeGate Team

Exam prep & CS education

Updated 6 Oct 20265 min read

You may understand individual Python statements but still lose the path when conditions and loops interact. Output-tracing questions and coding interviews punish one skipped branch, one wrong range() boundary, or one missing update. Use a working mental model, exact state traces, and clear rules for choosing if, for, and while; GATE does not prescribe Python.

Python control flow: sequence, selection and iteration

Control flow has three basic path shapes. A sequence executes statements in order. Selection chooses a suite of statements. Iteration repeats a suite. In Python, a colon opens a compound statement and indentation defines the suite controlled by it.

For any trace, record four things after each step: the current line, the condition value, changed variables, and output so far. Do not judge a condition only by how it looks. 0, 0.0, "", [], and None are falsy, while 7, "0", and [0] are truthy.

For a focused treatment of branch syntax, truthiness, nesting, and boundary traps, use Conditionals in Python. The traces below use branch order as one part of a larger state-change method.

Python if, elif and else: one branch from several choices

An if/elif/else chain tests conditions from top to bottom and executes only the first true suite. Comparisons and and, or, and not build each condition; short-circuiting can prevent a later expression from running.

python
readings = []
fallback = 7

if readings and 100 / readings[0] > 10:
    route = "use first reading"
elif fallback % 2 == 1:
    route = "odd fallback"
else:
    route = "even fallback"

print(route)

readings is empty and therefore falsy, so 100 / readings[0] is never evaluated. The elif test is true because 7 % 2 == 1, so Python assigns and prints odd fallback. The trace records both the chosen branch and the expression skipped by short-circuiting.

Separate if statements differ because several blocks may run. Use a single chain when exactly one route must be chosen.

Python for and while loops: two kinds of repetition

A for loop consumes items from an iterable; a while loop repeats while a changing state keeps its condition true. Loops in Python owns standalone syntax, range() boundaries, and isolated exercises. Here the focus is the invariant and state table behind one complete while trace.

A while loop repeats while its Boolean condition remains true. Euclid's algorithm is a useful state-driven example:

python
a, b = 84, 30
while b != 0:
    a, b = b, a % b
print(a)

Start at (84, 30). Since 84 % 30 = 24, the next state is (30, 24). Then 30 % 24 = 6 gives (24, 6). Finally, 24 % 6 = 0 gives (6, 0). Now b != 0 is false, so the loop stops and prints 6. Each update preserves the greatest common divisor while moving b toward zero.

Use for when consuming known iterable items. Use while when termination depends on changing state. For every while, identify the initial state, the update, and the stopping condition before running it.

Flowchart and step table for the GCD loop, tracing a and b from 84 and 30 to 6 and 0, then printing 6.

Python break, continue, pass and loop else

This factor search separates continue, break, and loop else in one trace:

python
candidate = 91
smallest_factor = None

for divisor in range(2, int(candidate ** 0.5) + 1):
    if candidate % divisor != 0:
        continue
    smallest_factor = divisor
    break
else:
    smallest_factor = candidate

print(smallest_factor)

Divisors 2 through 6 leave non-zero remainders, so continue skips the remaining body each time. At 7, 91 % 7 == 0; Python stores 7 and break exits. Because the exit used break, loop else is suppressed and the program prints 7.

If no divisor were found, normal exhaustion would run loop else and treat the candidate as prime. By contrast, pass is only a no-op placeholder; it neither skips an iteration nor exits the loop.

Nested loops: count the executed inner bodies

The inner loop need not run the same number of times for every outer value. This triangular traversal runs once, twice, then three times:

python
pairs = []

for row in range(1, 4):
    for column in range(1, row + 1):
        pairs.append((row, column))

print(pairs)

The visited pairs are (1, 1), (2, 1), (2, 2), (3, 1), (3, 2), and (3, 3). The inner body executes 1 + 2 + 3 = 6 times, not 3 x 3 times.

Python Loop Patterns and Idioms owns refactoring with enumerate(), zip(), comprehensions, and built-ins. Keep the explicit nested loop here because its changing inner bound is the behavior being traced.

Python tracing mistakes: overwritten state, wrong loop counts and misplaced else

Mistake

Observed result

Repair

Updating the GCD variables sequentially

The second assignment reads an already-overwritten value

Use parallel assignment: a, b = b, a % b

Counting the triangular loop as a 3 by 3 rectangle

The inner lengths are 1, 2, and 3, so the count is 6

List each executed inner range before adding

Attaching loop else to the last if

The else actually depends on normal loop exhaustion

Record whether break executed

These repairs all follow from the same four-column trace: current line, condition value, changed variables, and output so far. The method exposes overwritten state, wrong iteration counts, and incorrect control-transfer assumptions.

When debugging, trace the first three iterations, mark every skipped expression or statement, and test empty input plus one-item input before the normal case.

How GATE-style questions and interviews test control flow

Treat GATE-style questions as transferable program tracing, not evidence that a current paper requires Python. You should be able to derive the GCD states ending at (6, 0), explain why the factor search prints 7, and list the six triangular-loop pairs without executing the programs.

Interviews add design questions: which loop fits, why it terminates, what empty input does, where an off-by-one error sits, and how nesting changes the work. DSA Using Python is a follow-on path for applying these mechanics to interview problems.

For language semantics, use the official Python Language Reference. It defines iterable-driven for, condition-driven while, and the rule that break suppresses a loop's else.

Python control flow: the short version and next step

  • if selects one path.

  • for consumes an iterable.

  • while repeats until changing state makes its condition false.

  • continue skips the rest of one iteration.

  • break exits the loop and suppresses loop else.

Retrace the GCD states from (84, 30) to (6, 0), then prove why the factor loop stops at 7 and why the triangular loop executes exactly 6 inner bodies. If all three results match, the method is tracking control flow rather than guessing output.

For a structured path through concepts, MCQs, and coding, the Python course is an optional next step. If Python syntax already feels comfortable and you want interview applications, keep DSA Using Python as the separate follow-on.