Skip to content
Educora
IntermediateGrades 8–925 min31 / 59

Loops: for, while, step, break, continue and nested loops

`for` and `range(a, b, d)`, the number of iterations, counters and accumulators, the pre-condition `while` loop, trace tables, recurrences such as Fibonacci, `break`, `continue` and nested loops — with solved exam-style tasks.

Check yourself
In this lesson you will learn
  • Build for loops with range(a, b, d) and find the number of iterations without running the loop.
  • Use counter, accumulator and product variables with conditions inside a loop.
  • Trace while loops and recurrences with a trace table.
  • Determine the result of programs with break, continue and nested loops.

Suppose you must count the numbers from 1 to 1000 that are divisible by 7. Write if a thousand times? Never! A loop repeats a group of commands as many times as needed. In the four entrance-exam papers of 2025–2026 the most frequent topic was exactly “Loops. Operations on numbers”: 14 of the 120 informatics tasks. In this lesson you will learn to build loops and, above all, to trace them without mistakes using a trace table.

The for loop and range(): the step

Definition
Loop, loop body, iteration

A loop carries out a group of commands again and again. The repeated commands are the loop body (written with indentation), and one pass through the body is called an iteration. In a for loop the loop variable takes the next value of a sequence on every iteration: in for i in range(1, 6): i becomes 1, 2, 3, 4, 5 in turn.

The range function produces a sequence of whole numbers and has three forms: range(b) — 0, 1, …, b − 1; range(a, b) — a, a + 1, …, b − 1; range(a, b, d) — a, a + d, a + 2d, … The third number d is the step of the loop variable. With d > 0 the numbers grow until they reach b; with d < 0 they shrink until they reach b. The stop value b is never included — “up to b, without b”.

CallValuesIterations
range(5)0, 1, 2, 3, 45
range(3, 8)3, 4, 5, 6, 75
range(1, 20, 4)1, 5, 9, 13, 175
range(10, 0, -3)10, 7, 4, 14
range(20, 121)20, 21, …, 120101
range(8, 3)empty sequence0
N = ⌈(b − a) / d⌉N = ⌈(b − a) / d⌉
where:
  • Nthe number of iterations; if the expression is 0 or negative, the loop does not run at all
  • athe start value
  • bthe stop value (not included)
  • dthe step (may be negative)
  • ⌈x⌉x rounded up to the nearest whole number

The number of iterations of range(a, b, d). The last value of the loop variable is a + (N − 1) · d. With step 1 simply N = b − a; for all whole numbers of the interval [a, b] write range(a, b + 1), which gives N = b − a + 1.

Example 1. How many times does the loop run?

How many times does the loop body run, and what is the last value of the loop variable? 1) range(3, 20, 4); 2) range(15, 2, -4); 3) range(20, 121); 4) range(1, 10, -1).

Show solution
1) (20 − 3) / 4 = 4.25 → N = 5; last value 3 + 4 · 4 = 19 (3, 7, 11, 15, 19).
2) (2 − 15) / (−4) = 3.25 → N = 4; last value 15 + 3 · (−4) = 3 (15, 11, 7, 3).
3) Step 1: N = 121 − 20 = 101; last value 120.
4) (10 − 1) / (−1) = −9 < 0 → N = 0: the step is negative but the start is below the stop, so the loop never runs.
Python
for i in range(10, 0, -3):
    print(i)
print(len(range(3, 20, 4)), len(range(20, 121)))
▸ Expected output
10
7
4
1
5 101
A negative step gives decreasing values. len(range(…)) helps you check the number of iterations.

for works not only over range but over any sequence: for ch in 'Baku': takes the characters of a string one by one, and for x in [4, 9, 2]: the elements of a list. This will be used widely in the lessons “Strings and string operations” and “Lists and list operations”; in this lesson we work with numbers, that is, with range.

Counters and accumulators: conditions inside a loop

A loop often counts or adds up something. For that a variable gets a starting value before the loop and is updated inside the loop on every suitable iteration. A conditional statement inside the loop acts as a “filter”: only the values that satisfy the condition are counted or added.

  • counter: k = 0, in the loop k = k + 1 — how many times the condition held;
  • accumulator (sum): s = 0, in the loop s = s + x — the sum of the values;
  • product: p = 1 (not 0 — otherwise the result is always 0), in the loop p = p * x.
Python
s = 0
p = 1
k = 0
for i in range(1, 11):
    if i % 2 == 1:
        s = s + i
    else:
        p = p * i
    if i % 3 == 0:
        k = k + 1
print(s, p, k)
▸ Expected output
25 3840 3
From 1 to 10: the sum of the odd numbers s = 1 + 3 + 5 + 7 + 9, the product of the even numbers p = 2 · 4 · 6 · 8 · 10 and the count k of multiples of 3 (3, 6, 9).

The same pattern finds the largest (or smallest) value: before the loop mx gets the first value (or a number smaller than any possible one), and inside the loop if x > mx: mx = x is checked. So when the loop ends, mx holds the largest of the values seen. In all these patterns the loop looks at every value once and “collects” the result step by step.

K = b // m − (a − 1) // m
where:
  • Kthe number of naturals in [a, b] divisible by m
  • a, bthe ends of the interval (natural numbers)
  • mthe divisor

Counting without a loop: [1, b] holds b // m multiples of m; subtract those in [1, a − 1]. This is how we count instead of tracing loops over large ranges.

Example 2. Counting without writing a loop

Find: 1) how many numbers in [20, 120] are divisible by 7; 2) how many odd numbers lie in [25, 95]; 3) how many numbers in [1, 100] are divisible by 3 or 5.

Show solution
1) 120 // 7 − 19 // 7 = 17 − 2 = 15 (21, 28, …, 119).
2) Odd numbers go in steps of 2: (95 − 25) / 2 + 1 = 36.
3) 33 multiples of 3 and 20 multiples of 5; the 6 multiples of both (that is, of 15) were counted twice: 33 + 20 − 6 = 47.
Python
k = 0
for n in range(30, 131):
    if n % 2 == 0 and n < 100:
        if n % 7 == 0 or n % 9 == 0:
            k = k + 1
    else:
        k = k + 2
print(k)
▸ Expected output
141
The program of Example 3.
Example 3. An exam-style closed task: nested conditions inside a loop

Determine the result of the program above.
A) 141 B) 75 C) 132 D) 150 E) 139

Show solution
n takes 131 − 30 = 101 values in [30, 130]. Instead of tracing 101 iterations we split the numbers into two groups.
1) The outer condition is true (n even and n < 100): 30, 32, …, 98 — (98 − 30) / 2 + 1 = 35 numbers. Of these, only those divisible by 7 or 9 add 1 to k. Even and divisible by 7 = divisible by 14: 42, 56, 70, 84, 98 (5 numbers); even and divisible by 9 = divisible by 18: 36, 54, 72, 90 (4 numbers); none is divisible by both. Total +9.
2) The outer condition is false: 101 − 35 = 66 numbers, each adding 2: +132.
k = 9 + 132 = 141, answer A. Trap: whoever misses that the else belongs to the outer if attaches it to the inner condition and gets a different answer.

The while loop and the trace table

A while condition: loop repeats its body as long as the condition is true. The condition is checked before every iteration, so this is a pre-condition loop: if the condition is false from the start, the body does not run even once. The body must change a variable used in the condition, otherwise the loop never ends. When the loop finishes, the condition is false: the variable holds the first value that broke it. while is chosen when the number of repetitions is not known in advance: “until the sum passes 1000”, “until the digits of the number run out”.

Any for loop can be written with while: for i in range(a, b, d): (d > 0) is the same as i = a, while i < b:, the body, and i = i + d at the end of the body. This translation helps with the loops of flowcharts: there too the loop variable gets a start value, the condition is checked, and after the body the variable changes by the step (see “Loop algorithms and trace tables”).

Python
n = 0
k = 1
while k <= 15:
    n = n + k
    if k % 4 == 0:
        k = k + 1
    else:
        k = k + 3
print(n + k)
▸ Expected output
68
The program of Example 4.

A trace table writes down the variables row by row for every iteration: the value when the condition is checked, the result of the condition and the values after the body. For the program above:

kk <= 15nk % 4 == 0new k
1✓1✗4
4✓5✓5
5✓10✗8
8✓18✓9
9✓27✗12
12✓39✓13
13✓52✗16
16✗52—loop ends
Each row is one iteration. In the last row the condition is false and the body does not run.
Example 4. The result of a while loop

What does the program of Example 4 print?
A) 52 B) 64 C) 68 D) 71 E) 55

Show solution
The table shows 7 iterations: k takes the values 1, 4, 5, 8, 9, 12, 13, each added to n: n = 52.
In the last iteration k becomes 13 + 3 = 16, 16 <= 15 ✗ — the loop ends.
print(n + k) → 52 + 16 = 68, answer C. Option A (52) is for those who forget that k is added after the loop too.

When each new value is computed from earlier values, the loop produces a recurrence. The best known is the Fibonacci sequence: 1, 1, 2, 3, 5, 8, …, where every term is the sum of the two before it. In a program two variables hold the last two terms and “slide one step forward” on every iteration: c = a + b, a = b, b = c. The order of the assignments matters: if a = b came before c is computed, the old a would be lost.

Python
a = 1
b = 1
for i in range(3, 11):
    c = a + b
    a = b
    b = c
print(b)
▸ Expected output
55
The program of Example 5: on every iteration a and b hold the last two terms.
Example 5. The Fibonacci sequence

What does the program of Example 5 print, and which term of the Fibonacci sequence (1, 1, 2, 3, 5, …) is it?

Show solution
At the start a = 1, b = 1 — the 1st and 2nd terms. For each value of i, b becomes the i-th term:
i = 3: b = 2; i = 4: 3; i = 5: 5; i = 6: 8; i = 7: 13; i = 8: 21; i = 9: 34; i = 10: 55.
range(3, 11) gives 8 iterations, the last i is 10. Output: 55 — the 10th term.

break and continue

break stops the loop at once and completely: the remaining iterations are cancelled and the program goes to the line after the loop. continue does not stop the loop — it only skips the rest of the current iteration and moves on to the next one (in for the loop variable takes its next value, in while the condition is checked again). In nested loops both affect only the innermost loop. When a for loop is stopped by break, the loop variable keeps the value it had at that moment.

Python
s = 0
for i in range(1, 50, 3):
    if i % 5 == 0:
        continue
    if s > 40:
        break
    s = s + i
print(i, s)
▸ Expected output
19 41
The program of Example 6.
Example 6. break and continue together

What does the program of Example 6 print?

Show solution
Values of i: 1, 4, 7, 10, 13, 16, 19, …
i = 1: s = 1; i = 4: s = 5; i = 7: s = 12.
i = 10: 10 % 5 == 0 ✓ → continue, s stays 12.
i = 13: s = 25; i = 16: s = 41.
i = 19: 19 % 5 = 4, then 41 > 40 ✓ → break, 19 is not added.
The loop has stopped and i stays 19. Output: 19 41.
Python
n = 100
while True:
    n = n + 1
    if n % 7 == 0 and n % 13 == 0:
        break
print(n)
▸ Expected output
182
while True: never stops on its own — break provides the exit. The program finds the first number above 100 divisible by both 7 and 13: 91 · 2 = 182.

Nested loops

A loop body can contain another loop — these are nested loops. On every iteration of the outer loop the inner loop runs from start to finish, and the inner variable starts again each time. Think of a clock: when the minute hand (the outer loop) moves one mark, the second hand (the inner loop) makes a full circle. The inner loop’s limit may depend on the outer variable (range(i, 6)) — then the inner loop runs a different number of times on each outer iteration.

N = N₁ · N₂
where:
  • Nhow many times the inner body runs in total
  • N₁iterations of the outer loop
  • N₂iterations of one run of the inner loop

The product rule works when the inner loop does not depend on the outer variable. If it does, find the inner count for each outer iteration separately and add them up.

Example 7. How many times does the inner body run?

1) for i in range(4): with for j in range(1, 6): inside
2) for i in range(1, 5): with for j in range(i, 6): inside
3) for i in range(1, 6): with for j in range(i): inside

Show solution
1) Independent: 4 · 5 = 20.
2) i = 1: j 1…5 (5 times); i = 2: 4; i = 3: 3; i = 4: 2 → 5 + 4 + 3 + 2 = 14.
3) i = 1: once; i = 2: twice; … i = 5: 5 times → 1 + 2 + 3 + 4 + 5 = 15.
Python
for a in range(1, 25):
    for b in range(a, 25):
        if a * b == 24:
            print(a, b)
▸ Expected output
1 24
2 12
3 8
4 6
All pairs (a, b) with product 24 and a ≤ b. The inner loop starts at a so that repeated pairs such as (8, 3) are not printed.
Python
k = 0
for i in range(1, 5):
    for j in range(i, 6):
        if j % 4 == 0:
            break
        k = k + i
print(k)
▸ Expected output
10
The program of Example 8.
Example 8. An exam-style closed task: break in the inner loop

Determine the result of the program of Example 8.
A) 10 B) 20 C) 3 D) 14 E) 30

Show solution
break stops only the inner loop; when j reaches 4 the inner loop ends, but the outer one continues.
i = 1: j = 1, 2, 3 → 1 is added to k three times (k = 3); j = 4 → break.
i = 2: j = 2, 3 → 2 is added twice (k = 7); j = 4 → break.
i = 3: j = 3 → k = 10; j = 4 → break.
i = 4: j = 4 → break at once.
Answer: A) 10. Ignoring break gives 30 (E); thinking that it stops both loops gives 3 (C).
Exercise

Using a for loop and a counter, find and print how many numbers in [20, 120] are divisible by 3 but not by 5.

Exercise · Python
k = 0
# for n in range(...):

print(k)
▸ Expected output
27
Exercise

Use a while loop to find and print the first term of the Fibonacci sequence (1, 1, 2, 3, 5, …) that is greater than 1000.

Exercise · Python
a = 1
b = 1
# while ...:

print(b)
▸ Expected output
1597

Key points

  • range(a, b, d) starts at a, moves in steps of d and excludes b; the number of iterations is ⌈(b − a) / d⌉, or 0 if that is not positive.
  • A counter (k = 0), an accumulator (s = 0) and a product (p = 1) get their starting values before the loop and are updated inside it according to a condition.
  • while is a pre-condition loop: the condition is checked before every iteration, and after the loop the variable holds the first value that broke the condition.
  • break stops the loop completely, continue skips only the current iteration; in nested loops both belong to the innermost loop.
  • In nested loops the inner body runs N₁ · N₂ times (with a dependent limit, the sum of the inner counts); count big loops with trace tables and groups.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
Which values does range(2, 11, 3) give?