A. Programming Concepts and Skills · Programming Basics: Data, Decisions and LoopsRepetition 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.
- Python tests the condition.
- If it is True, the whole body runs once (one iteration), and Python goes back to step 1.
- 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:
- Initialize the loop control variable before the loop.
- Test it in the condition.
- Update it inside the body, so that the condition eventually becomes False.
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.
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 exampleExample 1: Tracing a loop
Trace this loop and give its output.
n = 1total = 0while n <= 4: total += n n += 1print(n, total)
- Before the loop: n = 1, total = 0.
- Test 1 ≤ 4: True. total = 0 + 1 = 1; n = 2.
- Test 2 ≤ 4: True. total = 1 + 2 = 3; n = 3.
- Test 3 ≤ 4: True. total = 3 + 3 = 6; n = 4.
- Test 4 ≤ 4: True. total = 6 + 4 = 10; n = 5.
- 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 exampleExample 2: Digits of a number
Write a loop that counts the digits of a positive integer n by repeatedly removing its last digit.
- Each
n = n // 10 removes the last digit (Lesson 4): 2026 → 202 → 20 → 2 → 0. - Count how many times that happens before
n reaches 0. - Code:
-
n = 2026
- digits = 0
- while n > 0:
- n = n // 10
- digits += 1
- print(digits) - 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 funWhy did the programmer never get out of the shower?
The shampoo bottle said: "Lather, rinse, repeat." No stopping condition!
Hands-on activityRoll until you get a six
You need: one ordinary die, paper, a pencil and Python.
- 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?
- Write down the loop in plain words: what is initialized, what is tested, what is updated?
- 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. - Add validation: if the roll is not from 1 to 6, print a message and do not count it.
- 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
1What is printed?
k = 3while k > 0: print(k) k -= 1print("Go!")
3, 2, 1, Go! on separate lines.
2How many times does the body run? What is printed?
x = 10while x < 10: x += 1print(x)
Zero times: 10 < 10 is False at the start. It prints 10.
3Why is this an infinite loop? Fix it.
i = 0while i < 5: print(i)
i is never updated, so i < 5 stays True. Add i += 1 inside the body (indented).
4Trace and give the output.
a = 1while a < 50: a = a * 3print(a)
a: 1, 3, 9, 27, 81. When a = 81 the test fails. Output: 81.
5Write a loop that prints the even numbers from 2 to 10.
Sample:
n = 2while n <= 10: print(n) n += 2
6Write a validation loop that keeps asking for a number of tickets until it is from 1 to 8.
Sample:
tickets = int(input("Tickets (1-8): "))while tickets < 1 or tickets > 8: tickets = int(input("Please enter 1 to 8: "))
7In a sentinel loop, why is the first value read before the loop?
So the condition has a value to test the first time, and so the sentinel is checked before it is processed (it is never added to the total).
More practice: warm-up
1When does a while loop stop?
When its condition is False at the moment it is tested.
2What key stops a program stuck in an infinite loop?
3What is one pass through a loop's body called?
4What starting value should an accumulator for a sum have?
5How many lines does this print?
c = 0while c < 3: print("hi") c += 1
More practice: on your own
1Trace and give the output.
n = 20steps = 0while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 steps += 1print(steps)
n: 20, 10, 5, 16, 8, 4, 2, 1. That is 7 updates. Output: 7.
2Write a program that reads positive numbers until the user enters −1, then prints how many were entered and their average (guard against no numbers).
Sample:
total = 0count = 0x = float(input("Number (-1 to stop): "))while x != -1: total += x count += 1 x = float(input("Number (-1 to stop): "))if count > 0: print(count, total / count)else: print("No numbers")
3This loop should print 5, 10, 15, 20 but prints nothing. Why?
n = 5while n > 20: print(n) n += 5
The condition is backwards: 5 > 20 is False at the start, so the body never runs. Use while n <= 20:.
4A bank account has $500 and earns 4% interest per year. Write a loop that finds how many years until it reaches at least $1000.
Sample:
balance = 500years = 0while balance < 1000: balance = balance * 1.04 years += 1print(years)
Output: 18 (after 17 years it is about $973.95; after 18, about $1012.91).
5Is this loop infinite? x = 1 then while x != 0: with body x = x - 0.1. Explain.
Yes, very likely. 0.1 cannot be stored exactly (Lesson 5), so after 10 subtractions x is a tiny number like 1.4e-16, not exactly 0, and it keeps going negative. Use while x > 0: instead.
Challenge
1Write a program that reads a positive integer and prints the sum of its digits using a while loop (e.g. 4096 → 19).
Sample:
n = int(input("Positive integer: "))total = 0while n > 0: total += n % 10 n = n // 10print(total)
n % 10 takes the last digit and n // 10 removes it: 6 + 9 + 0 + 4 = 19.
2Write 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.
Sample:
secret = 37guesses = 1guess = int(input("Guess: "))while guess != secret: if guess < secret: print("higher") else: print("lower") guess = int(input("Guess: ")) guesses += 1print("Correct in", guesses, "guesses")
Guesses 50, 25, 37 print lower, higher, then Correct in 3 guesses.
3Explain why the guessing game above needs a while loop rather than a fixed number of repetitions, and state the loop's three parts.
The number of guesses is unknown in advance. Initialize: the first guess is read (and guesses = 1) before the loop. Test: guess != secret. Update: a new guess is read at the end of the body, which can make the condition False.
Check your understandingQuiz
1. How many times does print run? i = 0 / while i < 4: / print(i) / i += 1
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 teachersBig 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.