24 min read
while Loops
Repeat while a condition is true — running totals with a sentinel, PIN attempts, and avoiding infinite loops.
The while Loop
A while loop repeats its block as long as its condition is True. Use it when you do not know in advance how many repeats are needed.
Counting with whilePython
count = 1while count <= 5: print("Count is", count) count += 1print("Done")Expected output
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done
The same three parts as a flowchart loop: start value (count = 1), condition (count <= 5) and change (count += 1).
Adding Prices Until 0
The sentinel loop from the flowchart course
Read this flowchart as text
- Terminator: Start (then → total = 0)
- Process: total = 0 (then → INPUT price)
- Input/output: INPUT price (then → price > 0?)
- Decision: price > 0? (Yes → total = total + price; No → OUTPUT total)
- Process: total = total + price (then → INPUT price)
- Input/output: OUTPUT total (then → Stop)
- Input/output: INPUT price (then → price > 0?)
- Terminator: Stop
till.pyPython
total = 0price = float(input("Price (0 to finish): ")) while price > 0: total += price price = float(input("Price (0 to finish): ")) print(f"Total: LKR {total:,.2f}")Expected output
Price (0 to finish): 250 Price (0 to finish): 480 Price (0 to finish): 120 Price (0 to finish): 0 Total: LKR 850.00
Notice the input line appears twice: once before the loop (to get the first price), and again at the end of the loop body (to get the next one). This is the standard pattern for a sentinel loop.
A Loop with Two Conditions
Up to three PIN attempts
Read this flowchart as text
- Terminator: Start (then → attempts = 0 pin = 0)
- Process: attempts = 0 pin = 0 (then → pin != 4321 and attempts < 3?)
- Decision: pin != 4321 and attempts < 3? (Yes → INPUT pin; No → pin == 4321?)
- Input/output: INPUT pin (then → attempts = attempts + 1)
- Decision: pin == 4321? (Yes → OUTPUT "Welcome"; No → OUTPUT "Card locked")
- Process: attempts = attempts + 1 (then → pin != 4321 and attempts < 3?)
- Input/output: OUTPUT "Welcome" (then → Stop)
- Input/output: OUTPUT "Card locked" (then → Stop)
- Terminator: Stop
pin.pyPython
attempts = 0pin = 0 while pin != 4321 and attempts < 3: pin = int(input("Enter PIN: ")) attempts += 1 if pin == 4321: print("Welcome")else: print("Card locked")Expected output
Enter PIN: 1111 Enter PIN: 4321 Welcome
for or while?
| for | while |
|---|---|
| You know how many times (or have a range to go through) | You repeat until something happens |
| The counter changes automatically | You must change the condition yourself |
| Print 10 labels; a times table | Add prices until 0; ask until the PIN is right |
Infinite Loops
An infinite loop — press Run and wait for it to be stoppedPython
count = 1while count <= 5: print(count)Practice
More lessons in Python Programming · Next: Functions · Previous: for Loops and range()
