While loops: keep going as long as it's true
A for loop knows how many trips to make. A while loop doesn't. It keeps going as long as its check stays true, however long that takes.
The big idea
A while loop repeats its pushed-in lines as long as its check is true, and stops the moment the check turns false.
See it in code
The check comes right after while. Python tests it before every trip. Here the loop runs while cookies are left:
cookies = 3
while cookies > 0:
print("Sold one! Cookies left:", cookies - 1)
cookies = cookies - 1
print("Sold out!")Sold one! Cookies left: 2 Sold one! Cookies left: 1 Sold one! Cookies left: 0 Sold out!
Each trip took one cookie away. When cookies reached 0, the check cookies > 0 turned false and the loop stopped.
A while loop is perfect for a line of customers. pop(0) takes the first order out of the list, so the line gets shorter every trip:
line = ["cookie", "brownie", "muffin"]
while len(line) > 0:
served = line.pop(0)
print("Ding ding! Now serving:", served)
print("The line is empty.")Ding ding! Now serving: cookie Ding ding! Now serving: brownie Ding ding! Now serving: muffin The line is empty.
len(line) counts the orders still waiting. Three orders meant three trips. You never had to say "three" anywhere.
A while loop can also keep asking a question until the answer is good. This one repeats as long as the order is not on the menu:
menu = ["brownie", "cookie", "muffin"]
order = input("What would you like? ").lower()
while order not in menu:
order = input("Sorry, we don't make that. Pick again: ").lower()
print("Coming right up:", order)What would you like? pizza Sorry, we don't make that. Pick again: taco Sorry, we don't make that. Pick again: cookie Coming right up: cookie
Two wrong answers meant two trips. The third answer was on the menu, so the check turned false and the program moved on.
Games are built on this idea. A game keeps running while the player has lives left. A shop keeps taking orders while customers keep asking for more.
Try it yourself
In the first program, change cookies = 3 to cookies = 6 and run it. The loop takes more trips by itself. Then change cookies - 1 to cookies - 2. How many trips now?
The common mistake
Forgetting to change the thing the check looks at. If you leave out cookies = cookies - 1, the check stays true forever and the loop never stops. Every trip must move you closer to the end.
What it unlocks
A while loop's check is a comparison. When you do know how many trips you need, a for loop is simpler. And lists that grow and shrink are covered in changing lists.