How Does While loops in Python are easy! ♾️ Work?

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! 🍪

Take the quiz →

Examples

  1. A while loop keeps asking if you want to play a game until you say no.
  2. Imagine counting from 1 to 10, but only stopping when you're tired.
  3. You keep eating cookies as long as there are still cookies left.

Ask a question

See also

Discussion

Recent activity

Categories: Science · Python· loops· programming