While Loops
Unlike for
loops, while
loops are non-deterministic – the program (and programmer!) doesn't
always know how many times the loop will repeat before it finally calls it quits. Instead, it
depends on a particular condition – usually waiting for a boolean
to flip from True
to False
. 🕵️♂️
Danger
If the condition never becomes False
, an infinite loop can be created. If you encounter
an infinite loop, usually Ctrl+C
will kill the program (for basic scripting).
(Don't worry, it happens to everyone! Even the pros forget to escape sometimes. 🏃♂️💨)
The basic form of a while
loop is:
The expression is evaluated at the start of each loop, and if it is True
, the loop will run.
It's like a party that keeps going as long as the music is playing! 🎶
For example:
Loop Until "Exit" | |
---|---|
Until the user enters "exit", this loop will keep echoing the user input infinitely. Careful not to get stuck in an infinite loop.
Tip
It is possible that a while
loop will never run if, when it is reached, the condition
it checks is already False
. 🚫
Another common pattern is to check equality and increment/decrement the value on each iteration:
Loop Until Value is Zero | |
---|---|
Challenge
Try writing your own while
loop that is different from the examples above!
Bonus points for creativity – maybe count sheep, print emojis, or make a countdown to pizza time! 🍕⏳