In short
Sometimes you don't know how many times to repeat: keep asking until the PIN is right, keep saving until you hit your goal. That is the while loop's job.
A while loop repeats as long as its condition is true, which suits cases where you don't know the number of repeats in advance, such as retrying input. Make sure something inside changes the condition, or it never stops.

Think of it like this
Filling a bucket at the tap
You don't decide "I'll fill exactly 37 mugs". You keep pouring while the bucket isn't full, checking each time. The moment it's full, you stop. If you forgot to check, water floods the bathroom. A while loop is that pour-and-check routine, and the flood is an infinite loop.
Watch it happen
Saving ₹750 a month until you reach ₹5,000
1/5savings is ₹1,000. Is it below ₹5,000? Yes, so enter the loop.
The big ideas
What you need to know
Condition checked every round
while condition: runs the block, then checks again. If the condition is False at the start, the block never runs at all.
Something must change
If nothing inside the loop affects the condition, it runs forever. Press Ctrl+C in the terminal to stop a runaway loop.
for or while?
Use for when you know what to loop over (a list, a range). Use while when you loop until something happens.
while True with break
A common pattern for menus and input retries: loop forever, and break out when you get what you need.
See it in code
Walk through the code
1savings = 10002months = 03while savings < 5000:4 savings += 7505 months += 16print(f"Goal reached in {months} months: ₹{savings}") # 6 months: ₹55007 8correct_pin = "4321"9attempts = 010pin = ""11while pin != correct_pin and attempts < 3:12 pin = input("Enter PIN: ")13 attempts += 114 15if pin == correct_pin:16 print("Unlocked")17else:18 print("Locked after 3 wrong tries")1/5The loop keeps going while savings is below the goal.
Two classic while loops: reach a target, and retry input with a limit.
Save yourself the pain
Common mistakes
Oops
Forgetting to update the variable, like while count < 5: print(count) with no count += 1.
Do this instead
Make sure the body changes something the condition depends on. If it's stuck, press Ctrl+C.
Oops
Using while with a manual counter to walk through a list.
Do this instead
Use a for loop for that. It can't go out of range and needs no counter.
Oops
Retrying input forever with no way out.
Do this instead
Add an attempts limit or a quit option, like typing q to exit.
Your mission
Keep asking
Quick check
x = 10; while x > 0: x -= 3. What is x after the loop ends?
Go deeper
- 1Keep asking for a PIN until the user enters the correct one.
- 2Write a loop that halves a number until it drops below 1 and counts the steps.
- 3Press Ctrl+C to stop an accidental infinite loop and then fix the condition.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.