⏳ While Loop
5th Grade 💻 Coding
A while loop repeats over and over as long as a certain condition is true, and stops the moment it isn’t.
A while loop is the right choice when you don’t know ahead of time how many repeats there will be: “While the player hasn’t guessed it, ask for another guess.” Before each repeat, the loop checks the condition. If it’s true, it runs the body of the loop; if not, the program moves on.
It’s important that something inside the loop changes the situation, or the condition will stay true forever. For example, in while count > 0: count = count - 1, count gets smaller on every repeat, finally reaches 0, and the loop stops. The similar Scratch block is “repeat until …,” which works the other way around: it repeats until the condition becomes true.
For example
- “While the glass isn’t full, keep pouring” is a while loop from the kitchen.
- A guessing game: while the guess is different from the secret number, ask for a new guess.
📌 Remember: while = “as long as.” Make sure something inside changes.
Quick quiz
When is a while loop the right choice?
When does a while loop stop?
What happens if nothing inside the loop ever changes?