while: Loop Until Done ๐ฌ
A for loop runs a set number of times. A while loop keeps going for as
long as something stays True โ however long that takes.
energy = 3
while energy > 0:
print(f"Zooming! Energy left: {energy}")
energy = energy - 1
print("Out of energy ๐ด")
Read it out loud: "while energy is more than zero, do this." Python checks the comparison, runs the indented block, then checks again, over and over, until the answer finally comes back False.
That line energy = energy - 1 looks weird but it's the most important one:
it means "take energy, subtract 1, put it back in energy."
โ ๏ธ The big warning: if you never change the variable inside the loop, the comparison stays True forever and your program never stops. Every while loop needs something inside it that moves toward the finish line!
Your mission
- Make a variable
candiesand set it to 10 - Write a
whileloop that keeps going whilecandiesis greater than 0 - Inside the loop: print how many are left, then subtract one
- After the loop ends, print an "all gone" message
Your code
Press โถ Run to see what your code does!