Hao
PRO
last year
Haocountry asked

Can you give a simpler explanation of how the while loop works? I still don’t fully get it.

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Hi Hao,

No problem — the while loop can be a bit confusing at first, but it’s actually pretty straightforward once you get the pattern.

A while loop runs a block of code over and over as long as a condition is true.

Here’s a simple example:

count = 1

while count <= 3:
    print("I am inside a loop.")
    print("Looping is interesting.")
    count = count + 1

print("OUTSIDE THE LOOP")

What’s happening here:

  1. count starts at 1

  2. The loop checks: is count <= 3?

    • If yes, it runs the code inside the loop

    • Then it increases count by 1

  3. It checks the condition again

  4. Once count becomes 4, the condition is no longer true, and the loop stops

Output:

I am inside a loop.
Looping is interesting.
I am inside a loop.
Looping is interesting.
I am inside a loop.
Looping is interesting.
OUTSIDE THE LOOP

So the loop runs 3 times, and then the program moves on.

The key is: if you forget to update the variable (count = count + 1), the condition might always be true — and the loop would run forever.

Let me know if anything's still unclear — I’m here to help.

Python
This question was asked as part of the Getting started with Python course.