PRO
Hao
asked

Expert
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:
countstarts at 1The loop checks: is
count <= 3?If yes, it runs the code inside the loop
Then it increases
countby 1
It checks the condition again
Once
countbecomes 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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer