while Loops: Repeat Until It Changes
A while loop repeats its block as long as a condition stays true. Before each pass, Python checks the condition. When it becomes false, the loop stops and the program moves on.
The single most important rule: something inside the loop must eventually make the condition false, or it runs forever. We call that the termination. Watch the counter climb until it fails the test:
count = 1
while count <= 3:
print(count)
count = count + 1 # this is what ends the loop
print("done")That prints 1, 2, 3, then done. Trace it: when count reaches 4, 4 <= 3 is false, so the loop ends. Forgetting the count = count + 1 line would loop forever, so always make sure each pass moves you toward the exit.
A common pattern is accumulating a total. Here we add numbers while a counter walks up:
total = 0
n = 1
while n <= 5:
total = total + n # total grows: 1, 3, 6, 10, 15
n = n + 1 # n moves toward the exit
print(total) # 15Read it as: start at the top, do the work, take one step toward stopping, repeat. The counter n both does the work and guarantees the loop ends.
Define a function sum_to(limit) that uses a while loop to add up all the whole numbers from 1 to limit (inclusive) and returns the total. For example sum_to(5) is 15. Make sure your counter changes every pass so the loop ends.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.