Keep going until you stop
Learn while loops β they keep repeating as long as a condition is true. Perfect for when you do not know how many times to repeat!
A while loop keeps repeating as long as a condition is True. It is like saying "keep doing this WHILE this is still true." The moment the condition becomes False, the loop stops.
π‘ Think of it like this:
Think of eating a bowl of cereal. You keep eating WHILE there is still cereal in the bowl. When the bowl is empty, you stop. A while loop works the same way!
While loops are perfect for situations where you do not know how many times to repeat. Keep asking for a password while it is wrong. Keep playing while the player wants to continue.
Where you see this in real life:
An infinite loop is a loop that never stops! It is a common bug β but sometimes it is intentional, like in game engines that keep running until you close the game.
A whileloop keeps repeating as long as a condition is True. The moment the condition becomes False, the loop stops.
We need a counter variable that changes inside the loop. If the condition never becomes False, we get an infinite loop that never stops!
count starts at 1 and goes up by 1 each time. When count hits 6, the loop stops.While loops can count down too! Great for rocket launches π
Click βΆ Run to see the output!If you forget to update the counter, the loop runs forever! This is called an infinite loop. Always make sure the condition can become False.
β Safe β counter changes
count = 0 while count < 3: print(count) count += 1
β Infinite β no change!
count = 0 while count < 3: print(count) # forgot to change count!
for loop
Use when you know how many times to repeat
Example: Print "Hi" 10 times
while loop
Use when you do not know how many times
Example: Keep asking until password is correct
What happens if you forget to update the counter variable in a while loop?