While loops in Python are like a robot that keeps doing a task until it’s told to stop.
Imagine you have a big bucket of marbles, and you want to count them all one by one. You start counting, and every time you take out a marble, you say “1, 2, 3…”, and you keep going until the bucket is empty. That’s what a while loop does! It keeps running your code while a certain condition is still true.
How it works
A while loop has two parts:
- A condition that checks if something is true (like “is the bucket not empty?”).
- The code block that runs over and over, as long as the condition stays true.
It’s like playing a game of “Simon Says”, you keep following the rules (“While I say ‘go,’ keep jumping!”) until the rule changes (“Now stop jumping!”).
A real-life example
Let's say you're eating cookies from a jar. You take one cookie, then another, and you keep doing that while there are still cookies left in the jar.
In Python code:
cookies_left = 10
while cookies_left > 0:
print("Yum! One more cookie!")
cookies_left -= 1
That’s how while loops work, simple, fun, and just like counting marbles or eating cookies! 🍪
Examples
- A while loop keeps asking if you want to play a game until you say no.
- You keep eating cookies as long as there are still cookies left.
Ask a question
See also
- What are infinite loops?
- What is while?
- What are while loops?
- How Does 6 Coding Concepts You MUST Know For Beginners Work?
- How Does 99% of Developers Don't Get Semaphores Work?