The while Loop in Python
while repeats as long as a condition holds. Use it when you do not
know in advance how many iterations you need.
i = 1 # 1. initialise
while i <= 5: # 2. condition
print(i)
i += 1 # 3. update
Same three parts as Module 2, same failure if you drop the update — an infinite loop.
Choosing between for and while
| Use | When |
|---|---|
for | The number of iterations is known: a fixed count, or every item of a sequence |
while | The stopping point is discovered during execution |
If you find yourself writing while with a counter you increment
yourself, a for is almost always clearer:
i = 0 # works, but
while i < len(items): # this is a for loop in disguise
print(items[i])
i += 1
for item in items: # say what you mean
print(item)
Sentinel-controlled input
total = 0
x = float(input("Enter a number (0 to stop): ")) # priming read
while x != 0:
total += x
x = float(input("Enter a number (0 to stop): "))
print("Sum is", total)
The priming read before the loop and the second read at the end of the body are both essential — exactly as in Module 2. Reading only at the top of the body would add the sentinel to the total.
The while True / break idiom
Python has no repeat-until. When you need at-least-once behaviour, this
is the standard replacement:
while True:
marks = int(input("Enter a mark (0-100): "))
if 0 <= marks <= 100:
break
print("Out of range, try again.")
This is the direct translation of Module 2's REPEAT … UNTIL marks >= 0 AND marks <= 100. Note the condition is not negated here — break
fires on the success case, whereas a while condition describes the
continue case. Getting that backwards is a common slip.
Infinite loops, in Python terms
while i < 10: # i never changes
print(i)
while x != 0.1: # float equality may never hold exactly
x -= 0.01
The second is a real trap and connects to the float discussion in the
selection topic: prefer < or > over == and != with floats.
If you do hang a program, Ctrl+C stops it.
while … else
Like for … else, the else runs only if the loop ended without
break:
while attempts < 3:
...
else:
print("Ran out of attempts")