while loops
A while loop repeats a block of code as long as a condition stays true.
Python
count = 1
while count <= 5:
print("Count is", count)
count += 1
print("Done!")Each time round the loop, Python checks the condition. When count reaches 6, count <= 5 is false and the loop ends.
The three parts of a counting loop
- Start: set up a variable before the loop (
count = 1). - Condition: decide when to keep going (
count <= 5). - Change: move towards the end inside the loop (
count += 1).
Forget the third part and the condition never becomes false.
Infinite loops
Python
n = 1
while n > 0:
n += 1That loop never ends, because n only grows. CodeMIRAI stops a program that runs too long; on your own computer you would press Ctrl + C.
Accumulating a result
Loops often build up a total:
Python
total = 0
n = 1
while n <= 100:
total += n
n += 1
print("1 + 2 + ... + 100 =", total)Looping until a condition is met
while shines when you don't know in advance how many times to repeat:
Python
savings = 1000
months = 0
while savings < 2000:
savings *= 1.01 # 1% growth per month
months += 1
print(f"Doubled after {months} months: {savings:.2f}")Reading input until the user stops
Python
total = 0
while True:
entry = input("Number (or 'done'): ")
if entry == "done":
break
total += int(entry)
print("Total:", total)while True: loops forever on purpose, and break (more on it soon) leaves the loop when the user types done.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.