Python Programming I
Senior 4 · ICT
Python Programming I
Lesson 4 of 5
25 min
Ishimwe opens a savings account with 1 000 Frw at a SACCO that adds 6 % interest at the end of each year (an illustrative rate). How many years until the balance reaches 2 000 Frw? You cannot know in advance how many times to add the interest; you have to keep going while the balance is below the target. That is exactly what Python's while loop does, and it is the Python form of the WHILE…ENDWHILE you met in Unit 3.
Definition
while loop: a statement that repeats its block as long as a condition is True, testing the condition before each pass: while condition: followed by an indented block.
Loop variable: a variable in the condition that the block changes, so that the condition eventually becomes False.
break: leaves the loop at once. continue: skips the rest of the block and goes back to test the condition.
Infinite loop: a loop whose condition never becomes False. In IDLE, press Ctrl + C to stop it.
Every while loop needs three things: a loop variable given a starting value, a condition that tests it, and a statement in the block that changes it. Press Run: the block runs 5 times, and the loop ends when count reaches 6.
Worked example 1: the doubling savings
Each year the balance is multiplied by . The loop keeps going while the balance is below 2 000 Frw.
| Year | balance < 2000? | Balance after the year (Frw) |
|---|---|---|
| 1 | 1 000: True | 1 060.00 |
| 2 | 1 060: True | 1 123.60 |
| … | … | … |
| 11 | 1 790.85: True | 1 898.30 |
| 12 | 1 898.30: True | 2 012.20 |
| (check) | 2 012.20: False, exit |
Answer: 12 years. Check with the formula for compound growth: and .
Run it to print the whole table. {years:2} pads the year to 2 characters and {balance:8.2f} prints 2 decimal places in a column 8 characters wide, so the numbers line up. Change rate to 0.09 and run again: how many years now?
A while loop can refuse bad input: keep asking while the answer is not acceptable. The block runs zero times if the first answer is good.
Run it and type 120, then −4, then 73: the first two are rejected and the third accepted. The input is read once before the loop and again at the end of each pass, the same pattern as the sentinel loop in Unit 3.
Python has no REPEAT…UNTIL. When the block must run at least once, write while True: (a loop that would never end on its own) and leave it with break when the stopping condition is met.
A guessing game. Run it and try 50, 25, 37. Each guess runs the block once; break ends the loop on the right guess. Halving the range each time (50, then 25, then about 37) finds any number from 1 to 100 in at most 7 guesses, because \( 2^7 = 128 \ge 100 \). (For a new number each game, a program can use random.randint(1, 100) from Python's random module.)
Worked example 2: skip with continue
A shopkeeper enters the day's sales one by one and types 0 to finish; a negative number is a typing mistake and must be ignored.
total = 0
while True:
sale = int(input("Sale (0 to finish): "))
if sale == 0:
break
if sale < 0:
print("Ignored")
continue
total += sale
print("Total sales:", total)Inputs 2500, −300, 1200, 0: 2500 is added; −300 prints "Ignored" and continue jumps back to the next input without adding; 1200 is added; 0 breaks. Output: Total sales: 3700.
Real Python: How to Use break and continue in Python while Loops. Watch how break leaves a loop and continue skips to the next pass, and follow the debugging of the example.
Warning
Change the loop variable. while count <= 5: with no count += 1 in the block prints for ever. Before running a loop, point to the line that will make the condition False.
Indent the whole body. A line meant to be inside the loop but typed at the left margin runs only once, after the loop has finished.
Floats rarely hit an exact value. Write while balance < 2000, not while balance != 2000: the balance jumps from 1898.30 to 2012.20 and never equals 2000, so the second version never stops.
Tip
Print inside the loop while testing. A temporary print(count, total) in the block shows each pass, which is a trace table produced by the computer. Remove it when the loop works.
Practice
n = 10, then while n > 0: print(n); n -= 3 (body on two indented lines).i = 1; total = 0; while i < 10: total += i; i += 1; print(total). Find the bug and evaluate two ways to fix it.count = 1), a condition that tests it (count <= 5), and a statement that changes it (count = count + 1).n = 2; while n <= 20: print(n); n += 2.while True: pw = input("Password: "); if pw == "Rwanda2026": print("Access granted"); break.n = 0; while 2 ** n <= 1000000: n += 1; print(n) gives 20, since and .a, b = 1071, 462; while b != 0: a, b = b, a % b; print(a) gives 21. (1071 = 2 × 462 + 147; 462 = 3 × 147 + 21; 147 = 7 × 21.)saved = 0; months = 0; while saved < 50000: saved += 3500; months += 1. 15 months, 52 500 Frw (after 14 months it is 49 000).i < 10 stops before 10 is added (1 + … + 9 = 45). Fix 1: while i <= 10. Fix 2: while i < 11. Both work; <= 10 is clearer because 10 is the number in the problem.Key points
while condition: repeats its indented block as long as the condition is True, testing before each pass, so the block may run zero times.while True with break gives a loop that runs at least once.break leaves the loop; continue skips to the next pass; Ctrl + C stops a runaway loop in IDLE.Sources and credits
This lesson adapts CC BY-SA material and is shared under CC BY-SA 4.0.
count = 1 # 1. start the loop variable
while count <= 5: # 2. test it
print("Pass number", count)
count = count + 1 # 3. change it
print("Finished; count is now", count)balance = 1000.0
rate = 0.06 # 6% a year (illustrative)
years = 0
while balance < 2000:
balance = balance * (1 + rate)
years += 1
print(f"Year {years:2}: {balance:8.2f} Frw")
print("Years to double:", years)mark = int(input("Mark (0-100): "))
while mark < 0 or mark > 100:
print("A mark must be between 0 and 100.")
mark = int(input("Mark (0-100): "))
print("Mark accepted:", mark)secret = 37 # the number to guess
tries = 0
while True:
guess = int(input("Your guess (1-100): "))
tries += 1
if guess == secret:
print(f"Correct! You needed {tries} tries.")
break # leave the loop
elif guess < secret:
print("Too low")
else:
print("Too high")Quick check
count = 1; while count < 4: print(count); count += 1. Which numbers are printed?