Python for Loops and while Loops Explained with Examples (range, break, continue)
P6.5 Python while Loop with Examples
Why. Sometimes you do not know how many times to repeat. You repeat until something happens: until the stock runs out, until the target is reached.
What. while condition: repeats as long as the condition is True. Something inside must change, or the loop never ends.
How.
Write a safe while loop
- Set the starting value.
- Write the condition.
- Change the value inside the loop.
- Check that the condition will become False.
Worked example A — Months to reach a savings goal.
Step 1 — What we do. A nurse in Dublin saves €300 a month to reach €2,000.
Step 2 — Type and run this code.
saved = 0
months = 0
while saved < 2000:
saved += 300
months += 1
print(months, "months, saved €", saved)
Step 3 — Output you should see.
7 months, saved € 2100
Step 4 — What it means. The loop repeats until saved reaches 2000 or more: 7 months.
Worked example B — Stock runs down.
Step 1 — What we do. A shop sells 40 units a day from 150 units.
Step 2 — Type and run this code.
stock = 150
day = 0
while stock > 0:
day += 1
stock -= 40
print("Out of stock on day", day)
Step 3 — Output you should see.
Out of stock on day 4
Step 4 — What it means. Day 4 the stock goes to zero or below. -= is short for "subtract".
Ravindra Bagale's Tip
If Jupyter keeps running forever, your while condition never becomes False. Press the ■ stop button (Interrupt the kernel) and fix the change inside the loop.
Ravindra Bagale's Tip – मराठी
Jupyter सतत चालूच राहिलं तर तुमची while condition कधी False होत नाही. ■ stop button दाबा (kernel interrupt) आणि loop मधला बदल दुरुस्त करा.
Ravindra Bagale's Tip – हिंदी
Jupyter लगातार चलता रहे तो आपकी while condition कभी False नहीं होती. ■ stop button दबाओ (kernel interrupt) और loop के अंदर का बदलाव ठीक करो.