TutreNews Learn

Decisions and loops

while loops

Goal: Repeat code while a condition holds · 8 min

A while loop repeats its block as long as the condition is True. Each pass is called an iteration.

n = 1
while n <= 3:
    print(n)
    n += 1

Something inside the loop must eventually make the condition False — otherwise you get an infinite loop. break leaves a loop immediately; continue skips to the next iteration.

Worked example: Doubling until over 100

  1. Start x = 1, count steps.
  2. 1 → 2 → 4 → … → 128 needs 7 doublings.
  3. Output: 7 128
x = 1
steps = 0
while x <= 100:
    x *= 2
    steps += 1
print(steps, x)

Output:

7 128