The Infinite Trap
Hoppy enters a room that locks behind him. A sign says: "Charge the crystal until it is full."
Sometimes you don't know exactly how many steps it will take. You just know you need to keep going while a condition is true.
The While Loop
A while loop is like an if statement that repeats. It keeps running as long as the condition is True.
water_level = 0
while water_level < 3:
print("Adding water...")
water_level = water_level + 1
print("Cup is full!")
Your Mission
Create a variable energy and set it to 0.
Write a while loop that runs as long as energy < 10.
Inside the loop, increase energy by 1 (energy = energy + 1).
Inside the loop, print the energy so you can see it rising.
If you forget to increase energy, the condition energy < 10 will ALWAYS be true, and the loop will run FOREVER (or until the Watchdog stops it). This is an Infinite Loop.
Suggested SolutionClick to expandClick to collapse
Charge it up:
energy = 0 while energy < 10: energy = energy + 1 print(energy)
Advanced TipsWant more? Click to expandClick to collapse
Use for when you know how many times (iterate over a range or list).
Use while when you are waiting for a condition to change (like waiting for a user to type "quit").