Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Repetition with while Loops

A2.2 A2.1 A4.4About 70 minutes
Learning goals
  • I can write a while loop with a correct starting value, condition and update.
  • I can trace a loop with a trace table and predict its output.
  • I can use a loop to count, to total, and to repeat until the user enters a sentinel value.
  • I can use a loop to validate input.
  • I can recognize and stop an infinite loop.

Words to know

repetition (loop)
A control structure that runs a block of statements again and again.
while loop
A loop that repeats its body as long as its condition is True. The condition is tested before each pass.
iteration
One pass through the body of a loop.
loop control variable
The variable the loop condition depends on. It must be given a starting value and be updated inside the loop.
infinite loop
A loop whose condition never becomes False, so it never ends.
sentinel value
A special input, such as 0 or -1, that signals the end of the data and stops the loop.
accumulator
A variable that builds up a total, such as total += price, starting from 0.

Doing it again

A snow-clearing program checks the driveway sensor again and again until the snow stops. A game asks for guesses until you get it right. Writing the same line 100 times is not programming. Repetition, the third control structure, lets one block of code run as many times as needed.

Python has two loops. This lesson is about the while loop, which repeats as long as a condition is True. Lesson 12 covers the for loop.

How a while loop works

  • while condition: then an indented body.
  1. Python tests the condition.
  2. If it is True, the whole body runs once (one iteration), and Python goes back to step 1.
  3. If it is False, the loop ends and Python continues with the first line after the body.

If the condition is False the very first time, the body runs zero times.

Every correct while loop has three parts:

  1. Initialize the loop control variable before the loop.
  2. Test it in the condition.
  3. Update it inside the body, so that the condition eventually becomes False.
savings = 20week = 0savings < 100 ?Truesavings += 15week += 1repeatFalseprint(week, savings)
A while loop: test the condition; if True, run the body and go back to test again. When the condition becomes False, the loop ends and the program continues below it.
savings = 20
week = 0
while savings < 100:
savings += 15
week += 1
print(f"After {week} weeks you have ${savings}.")

Saving $15 a week from a start of $20 until there is at least $100. Output: After 6 weeks you have $110.

goal 10020week 035week 150week 265week 380week 495week 5110week 6
The value of savings each time the condition is tested. After week 6 it is 110, the condition savings < 100 is False, and the loop stops. The body ran 6 times.
Worked example

Example 1: Tracing a loop

Trace this loop and give its output.

  • n = 1
  • total = 0
  • while n <= 4:
  •     total += n
  •     n += 1
  • print(n, total)
  1. Before the loop: n = 1, total = 0.
  2. Test 1 ≤ 4: True. total = 0 + 1 = 1; n = 2.
  3. Test 2 ≤ 4: True. total = 1 + 2 = 3; n = 3.
  4. Test 3 ≤ 4: True. total = 3 + 3 = 6; n = 4.
  5. Test 4 ≤ 4: True. total = 6 + 4 = 10; n = 5.
  6. Test 5 ≤ 4: False. The loop ends after 4 iterations.

Output: 5 10. Notice n is 5 after the loop: one more than the last value used. The condition was tested 5 times but the body ran 4 times.

Infinite loops

If the update is missing or goes the wrong way, the condition never becomes False:

  • while n <= 4: with no n += 1 in the body repeats forever.
  • while n != 10: with n += 3 starting from 0 skips over 10 (0, 3, 6, 9, 12, ...) and never stops.

To stop a runaway program, press Ctrl+C (in IDLE, you can also close the shell window or choose Shell → Restart Shell). Then fix the loop. Using < or <= instead of != in a condition is a safer habit.

Sentinel loops: repeat until a special value

Often you do not know how many times to repeat. For example, a cashier enters prices until the order is done. A sentinel value marks the end. The usual pattern reads one value before the loop and the next value at the end of the body:

total = 0
count = 0
price = float(input("Price (0 to finish): "))
while price != 0:
total += price
count += 1
price = float(input("Price (0 to finish): "))
print(f"{count} items, total ${total:.2f}")

The sentinel (0) is never added to the total. count and total are accumulators that start at 0. Output, line by line: Price (0 to finish): 3.5 | Price (0 to finish): 12.25 | Price (0 to finish): 0 | 2 items, total $15.75 (the typed input is shown after each prompt)

Validation loops

A while loop can keep asking until the input is acceptable. The condition describes bad input:

mark = int(input("Mark (0 to 100): "))
while mark < 0 or mark > 100:
print("Out of range. Try again.")
mark = int(input("Mark (0 to 100): "))
print("Recorded:", mark)

The loop body runs only while the mark is invalid. A valid first answer skips the loop completely. Output, line by line: Mark (0 to 100): 140 | Out of range. Try again. | Mark (0 to 100): -5 | Out of range. Try again. | Mark (0 to 100): 87 | Recorded: 87 (the typed input is shown after each prompt)

`break`

Python also has break, which leaves a loop immediately, usually inside an if. It is handy, for example while True: ... if guess == secret: break. But a loop with a clear condition is easier to trace, and many teachers ask you to use break sparingly. Never write while True: without a break you can reach.

Worked example

Example 2: Digits of a number

Write a loop that counts the digits of a positive integer n by repeatedly removing its last digit.

  1. Each n = n // 10 removes the last digit (Lesson 4): 2026 → 202 → 20 → 2 → 0.
  2. Count how many times that happens before n reaches 0.
  3. Code: - n = 2026 - digits = 0 - while n > 0: -     n = n // 10 -     digits += 1 - print(digits)
  4. Trace: (n, digits) = (2026, 0), (202, 1), (20, 2), (2, 3), (0, 4). The condition 0 > 0 is False, so it stops.

It prints 4. (For n = 0 the loop runs zero times and prints 0, a case you would handle separately.)

Just for fun

Why did the programmer never get out of the shower?

The shampoo bottle said: "Lather, rinse, repeat." No stopping condition!

Hands-on activity

Roll until you get a six

You need: one ordinary die, paper, a pencil and Python.

  1. Roll the die until you get a 6. Keep a trace table: roll number, value rolled, "is it 6?". Do this three times. How many rolls did each round take?
  2. Write down the loop in plain words: what is initialized, what is tested, what is updated?
  3. Write a program where you type each roll: it keeps asking Roll: until you type 6, then prints how many rolls it took. Use the read-before-the-loop pattern.
  4. Add validation: if the roll is not from 1 to 6, print a message and do not count it.
  5. Run it with your real rolls and check the count against your paper trace.

What to look for: a correct program reads one roll before the loop, uses while roll != 6:, counts and reads again at the end of the body, and adds 1 for the final six (or starts the count at 1). Your three rounds will probably take different numbers of rolls; that is why a while loop, not a fixed count, is the right tool.

Your turn

1

What is printed?

  • k = 3
  • while k > 0:
  •     print(k)
  •     k -= 1
  • print("Go!")
2

How many times does the body run? What is printed?

  • x = 10
  • while x < 10:
  •     x += 1
  • print(x)
3

Why is this an infinite loop? Fix it.

  • i = 0
  • while i < 5:
  •     print(i)
4

Trace and give the output.

  • a = 1
  • while a < 50:
  •     a = a * 3
  • print(a)
5

Write a loop that prints the even numbers from 2 to 10.

6

Write a validation loop that keeps asking for a number of tickets until it is from 1 to 8.

7

In a sentinel loop, why is the first value read before the loop?

More practice: warm-up

1

When does a while loop stop?

2

What key stops a program stuck in an infinite loop?

3

What is one pass through a loop's body called?

4

What starting value should an accumulator for a sum have?

5

How many lines does this print?

  • c = 0
  • while c < 3:
  •     print("hi")
  •     c += 1

More practice: on your own

1

Trace and give the output.

  • n = 20
  • steps = 0
  • while n != 1:
  •     if n % 2 == 0:
  •         n = n // 2
  •     else:
  •         n = 3 * n + 1
  •     steps += 1
  • print(steps)
2

Write a program that reads positive numbers until the user enters −1, then prints how many were entered and their average (guard against no numbers).

3

This loop should print 5, 10, 15, 20 but prints nothing. Why?

  • n = 5
  • while n > 20:
  •     print(n)
  •     n += 5
4

A bank account has $500 and earns 4% interest per year. Write a loop that finds how many years until it reaches at least $1000.

5

Is this loop infinite? x = 1 then while x != 0: with body x = x - 0.1. Explain.

Challenge

1

Write a program that reads a positive integer and prints the sum of its digits using a while loop (e.g. 4096 → 19).

2

Write a number-guessing loop: the secret is stored in secret = 37. The user guesses until correct; after each wrong guess print higher or lower. At the end print the number of guesses.

3

Explain why the guessing game above needs a while loop rather than a fixed number of repetitions, and state the loop's three parts.

Check your understanding

Quiz

1.

How many times does print run? i = 0 / while i < 4: / print(i) / i += 1

2.

Which loop is infinite?

3.

A loop reads values until the user enters 0. What is 0 called?

4.

After x = 1 / while x < 20: / x = x * 2, what is x?

5.

When is a while condition tested?

6.

Which condition is right for a validation loop that rejects ages below 0 or above 120?

For parents and teachers

Big idea: expectation A2.2 (repetition) with input loops (A2.1) and tracing (A4.4).

How to help: play the dice activity together, and ask your teen to say the loop's three parts out loud: what starts it, what is tested, what changes each time. If a program freezes, show them Ctrl+C.

Common difficulties:

  • Forgetting the update, causing an infinite loop.
  • Off-by-one errors (< versus <=). A trace table settles it.
  • Forgetting to read the next input at the end of a sentinel loop, or adding the sentinel to the total.
  • Writing the validation condition for good input instead of bad input.