1.2.17Introduction to Programming (Python)

while loop — condition-based, infinite loop dangers

1,780 words8 min readdifficulty · medium

WHAT it is

The three pieces you ALWAYS need:

  1. Initialise — a variable exists before the loop.
  2. Condition — a boolean that uses that variable.
  3. Update — something inside the body that pushes the condition toward False.

WHY it exists (and HOW it runs)

HOW Python executes it (step trace):

i = 1                # 1. initialise
while i <= 3:        # 2. check condition  -> True?
    print(i)         # 3. run body
    i = i + 1        # 4. update -> go back to step 2

Trace table (Why this step? = "show every check, including the final one that fails"):

Step i i <= 3? Action
check 1 True print 1, i→2
check 2 True print 2, i→3
check 3 True print 3, i→4
check 4 False exit loop

The condition is checked 4 times to print 3 numbers — the last check is the one that ends it. Forgetting this off-by-one is the #1 bug source.

Figure — while loop — condition-based, infinite loop dangers

Worked examples


The infinite-loop danger


Recall Feynman: explain to a 12-year-old

Imagine you're filling a bucket with a cup. Before each scoop you peek inside and ask: "Is the bucket still not full?" If yes, you scoop again. If the bucket is full, you stop. The "peek" is the condition, the "scoop" is the body, and pouring water in is the update. If you peek but never actually pour water (no update), the bucket is never full — so you scoop forever and your arm falls off. That endless scooping is an infinite loop.


Flashcards

When is a while loop's condition evaluated relative to the body?
Before each iteration (pre-test loop); the body may run zero times.
What causes an accidental infinite loop?
A condition that never becomes False — usually a missing or misplaced update statement.
Difference between for and while in intent?
for = known/finite iteration count; while = repeat until a condition changes, count unknown in advance.
Why avoid while x == target: with floating-point updates?
Float arithmetic rarely lands exactly on a value; the condition may skip the target and loop forever. Use </> comparisons instead.
What does break do inside while True:?
Immediately exits the loop, providing the real, controlled stop for an intentionally infinite loop.
In while i <= 3: print(i); i+=1 starting i=1, how many times is the condition checked?
4 times (3 True + 1 final False that ends it).
What key combo stops a runaway loop in a terminal?
Ctrl + C.
What error does while x = 5: produce?
SyntaxError — = is assignment, you need == for comparison.

Connections

Concept Map

is a

runs body while

checked before

needs 3 parts

needs 3 parts

needs 3 parts

used by

pushes toward

causes

if forgotten

preferred over for when

while loop

pre-test loop

condition True

each iteration

Initialise variable

Boolean condition

Update in body

condition False

exit loop

infinite loop

iteration count unknown

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, while loop ka idea bahut simple hai: computer har baar body chalane se pehle ek sawaal poochta hai — "condition abhi bhi True hai kya?". Jab tak haan, body dobara chalegi; jaise hi False hua, loop ruk jaata hai aur program aage badh jaata hai. Isiliye isko pre-test loop kehte hain. for loop tab use karo jab tumhe pata ho kitni baar chalana hai; while tab jab repetitions data ya user input pe depend karein aur count pehle se na pata ho.

Sabse important cheez yaad rakho: teen ingredients hote hain — Initialise, Condition, Update (mnemonic: "I C U"). Variable pehle banao, condition usi pe likho, aur body ke andar uss variable ko aise badlo ki dheere-dheere condition False ki taraf jaaye. Agar tumne update bhool gaye (jaise i += 1 nahi likha), to condition kabhi False nahi hogi aur loop hamesha chalta rahega — yahi hai infinite loop ka danger. Program hang ho jaata hai.

Ek aur common trap: float ke saath == mat lagao (while x != 1.0). Float arithmetic kabhi exact value pe nahi rukti, isliye < ya > use karo. Aur agar accidentally infinite loop chal pade terminal me, to ghabrao mat — Ctrl + C dabao, loop turant mar jaayega.

while True: ko dekh ke darna nahi — wo deliberate pattern hai jisme andar break hota hai jo asli exit deta hai. Bug sirf tab hai jab infinite loop galti se ban jaaye. Bas yaad rakho: condition "stop sign" hai, lekin uski taraf gaadi (update) chalni bhi chahiye, warna gaadi kabhi pahunchegi hi nahi.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections