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

Trace Python if, for and while execution through branch order, range boundaries, number reversal, loop jumps, nesting and edge cases.

KnowledgeGate Team

Exam prep & CS education

Updated 13 Nov 20267 min read
Python Control Flow and Looping: if, for, while and Worked Traces

Python's if, for and while syntax is short, but branch order, changing state, jumps and nesting make output traces easy to misread. Start with Python Control Flow and Loops: if, for, while and Worked Traces for core syntax, the selection-and-iteration model, and termination rules. For each trace, record the current line, condition result, changed variables and output after every executed step.

Python execution ledgers expose branch order, truth values and indentation

Control flow is the order of execution. A program can select a path with if or match, repeat work with for or while, or redirect execution with a jump. Selection and repetition determine which statements run and how often.

Indentation creates each suite, or block. In an if chain, Python runs only the first branch whose condition is true:

python
weight_kg = 6
distance_km = 240

if weight_kg > 20:
    charge = "freight desk"
elif distance_km > 500:
    charge = "long haul"
elif weight_kg > 5:
    charge = "standard plus"
else:
    charge = "standard"

print(charge)

The tests are 6 > 20, which is False; 240 > 500, also False; then 6 > 5, which is True. Python assigns and prints standard plus. It does not inspect the final else after finding that true branch. Order carries the meaning here: lift the weight_kg > 5 test above the freight check and a 25 kg parcel would stop at standard plus instead.

Zero, None, empty strings and empty containers are false; non-empty values are normally true. Short-circuiting prevents unsafe work: with records = [], records and records[0] returns [] without attempting index 0.

match branches on structure. With command = ("move", 3), case ("move", steps) if steps > 0 binds steps to 3. It does not replace every if.

Python for-loop trace: filter values and update two results

A for loop visits values from an iterable. Use indexes only when meaningful. list(range(3, 16, 4)) is [3, 7, 11, 15]: start included, stop excluded. With scores = [72, 85, 64], enumerate(scores, start=1) yields (1, 72), (2, 85) and (3, 64).

Consider filtering and accumulating together:

python
values = [3, 8, 5, 12, 7]
even_squares = []
even_sum = 0

for value in values:
    if value % 2 == 0:
        even_squares.append(value * value)
        even_sum += value

All values are visited, but only 8 and 12 pass. Thus even_squares becomes [64, 144] and even_sum becomes 20. The list always contains the squares of even items seen so far.

Use Loops in Python: for, while, range(), break and continue for standalone loop syntax, range boundaries and isolated exercises. The combined trace above is different: it filters each value while updating both even_squares and even_sum. Separately, range(10, 0, -4) produces 10, 6, 2, so its body runs 3 times.

Python while-loop trace: prove number reversal terminates

Use while when repetition ends because state changes, not because an iterable is exhausted. It needs an initial state, a guard and an update that can make the guard false.

This program reverses a non-negative integer:

python
n = 173
reversed_n = 0

while n > 0:
    digit = n % 10
    reversed_n = reversed_n * 10 + digit
    n //= 10

print(reversed_n)

Point

digit

n

reversed_n

Start

not set

173

0

After iteration 1

3

17

3

After iteration 2

7

1

37

After iteration 3

1

0

371

The arithmetic is 0 * 10 + 3 = 3, then 3 * 10 + 7 = 37, then 37 * 10 + 1 = 371. Now n > 0 is false. Without n //= 10, n stays 173 and the loop never terminates.

Input 0 performs no iterations and leaves reversed_n at 0. Negative input needs a sign policy. After each round, reversed_n reverses the digits removed from the original number.

Flowchart of the reverse-number while loop, with n = 173 falling to 0 across three passes while reversed_n grows to 371.

Python jump trace: separate break, continue, pass and loop else

These statements alter different scopes:

Statement

Immediate effect

Scope

break

Exits immediately

Nearest loop

continue

Skips the rest of this iteration

Nearest loop

pass

Does nothing; acts as a placeholder

Current suite

return

Sends control back to the caller

Current function

A loop's else runs after normal completion, including zero iterations, but not after break.

Suppose values = [9, 14, 21, 28]. A search assigns found_at = index and breaks on the target; its else assigns -1. For target 21, it checks indexes 0, 1, 2, then returns 2 and skips else. For target 25, it checks all four values and returns -1.

With readings = [4, -1, 7, -3, 6], continue skips negatives, giving 4 + 7 + 6 = 17. Replacing it with pass would not skip addition. Use pass only for an empty placeholder.

Nested Python loop trace: follow continue and break in two dimensions

Trace the inner loop separately for each outer value:

python
total = 0

for i in range(1, 4):
    for j in range(1, 5):
        if j == 2:
            continue
        product = i * j
        if product > 6:
            break
        total += product

print(total)

For i = 1, add 1 to get 1, continue at j = 2, add 3 to get 4, then add 4 to get 8. For i = 2, add 2 to get 10, continue at j = 2, add 6 to get 16, then break at j = 4 because 2 * 4 = 8 > 6. For i = 3, add 3 to get 19, continue at j = 2, then break at j = 3 because 3 * 3 = 9 > 6. The final output is 19.

Both jumps affect only the inner loop, and product is not evaluated at j = 2 because continue comes first. The two-dimensional ledger also proves that j = 4 is never visited when i = 3.

Grid tracing the nested loop for i = 1 to 3 and j = 1 to 4, marking each continue and break, with the running total ending at 19.

Python refactor checkpoint: preserve traced results with comprehensions

The earlier filter becomes [value * value for value in values if value % 2 == 0], producing [64, 144]. For the same list, filtered sum(...) is 20, any(value > 10 for value in values) is True, and all(value > 0 for value in values) is True.

Use a comprehension for one expression and a clear filter. Keep an explicit loop for changing state, multiple branches, logging, breaks or debugging. The total-19 example needs explicit loops to expose its jump paths.

Use Python Loop Patterns and Idioms: A Practical Tutorial for enumerate, zip, dictionary traversal and readability refactors. The checkpoint here is narrower: the compact expression must preserve the traced results [64, 144] and 20. Do not remove items from a list while iterating; build a new list or iterate over a copy.

Python assessments: trace output, iteration counts and boundaries

Treat GATE-style pseudocode as a trace. Write the variable sequence and count executed bodies before deriving output or complexity. In for i in range(1, 4): for j in range(i): count += 1, the counts are 1 + 2 + 3 = 6. From n = 40, repeated n //= 2 produces 20, 10, 5, 2, 1: 5 iterations.

For interviews, test empty input, one item, an absent target, zero, negatives and duplicates. An empty search reaches else and returns -1; reversing 0 leaves 0; negatives require a sign decision.

Prompt shape

Trace action

Self-check

Predict output

Record each assignment

Did branch order change the path?

Count iterations

List produced states or values

Did I include only executed bodies?

Refactor to a comprehension

Identify expression and filter

Is the result still readable?

Repair non-termination

Find the missing state update

Must the guard become false?

Test boundaries

Try empty, zero and absent cases

Is behaviour explicitly defined?

Use the Coding & DSA Courses for Placements category when these trace mechanics are secure and you want to apply them to searching, traversal and interview problems.

Python control flow worked traces: verified outputs and next step

Keep six rules in view:

  1. Evaluate if branches in order.

  2. Remember that range excludes its stop.

  3. Prove that a while update can reach termination.

  4. Distinguish break, continue and pass.

  5. Trace nested loops one outer row at a time.

  6. Test boundary inputs before trusting the main case.

Checkpoints: the conditional prints standard plus; the range gives [3, 7, 11, 15]; reversal gives 371; searches give 2 or -1; the nested trace gives 19.

If you want the wider language sequence plus guided practice, use Python Course: Concepts, MCQs & Coding as the structured next step.