1.2.17 · D1Introduction to Programming (Python)

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

3,062 words14 min readBack to topic

This page assumes you have seen nothing. Before you can understand the while loop, you must own every small symbol it leans on. We build them one at a time, each with a picture, in an order where each brick sits on the one below it. Nothing below uses a symbol we have not already unpacked — including the word while itself, which we deliberately hold back until the very end.


0. Values: numbers and text (the two kinds of "stuff")

Before any box or command, we need the stuff that goes inside a program.

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

Look at the figure: on the left a number 5 sits bare; on the right the same digit lives inside quote-fences as the text "5". The topic needs both — numbers to count down a loop, text to show messages and to read what a user types.


1. What is a "variable"? (the box with a name)

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

Look at the figure: the label n is painted on the outside of the box; the value 5 sits inside. The label never changes, but the contents can be swapped out whenever a line of code tells them to. How you put something into the box is the job of the = sign, which we define next — so for now, just picture the box existing.


2. Arithmetic first: + and - (the compute symbols)

Before we can even change a box, we need the two symbols that do arithmetic. We meet these first, so that when the assignment command uses them, they are already familiar.

Keep these two in your pocket; the very next section puts them to work.


3. The = sign is a command, not a fact (assignment)

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

Follow the three arrows in the figure for n = n + 1:

  1. Read the current contents of n (say, 5).
  2. Compute 5 + 1 = 6 off to the side (that is the + operator working).
  3. Write the 6 back into the box n, erasing the old 5.

This is the update step the parent note calls the loop's engine. Without a line like this, the box never changes, and the loop's question keeps getting the same answer forever.

Shorthand: n += 1 is just a shorter way to write n = n + 1, and n -= 1 is a shorter way to write n = n - 1. They perform exactly the same read → compute → write dance, reusing the + and - operators. Whenever you see += or -=, mentally expand it to the longer form.


4. Comparison: ==, !=, <, >, <=, >=

You write You read it as Answers True when…
a == b "is a equal to b?" the two values match
a != b "is a not equal to b?" they differ
a < b "is a less than b?" a is smaller
a > b "is a greater than b?" a is bigger
a <= b "is a at most b?" a smaller or equal
a >= b "is a at least b?" a bigger or equal

Why does a loop need these? Because the loop's stop-sign — its condition — is built from a comparison. The line n > 0 literally means "is the answer to 'is n bigger than 0?' yes?"


5. True and False — the only two answers (Booleans)

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

Picture a light switch: it is either ON (True) or OFF (False), never halfway. A loop will flip this switch based on the current contents of the boxes. ON → run the body once more. OFF → stop.


6. Combining answers: and, or, not (logical operators)

Sometimes one yes/no question is not enough — a loop may need two conditions true at once, or either of two, or the opposite of one. Three keywords glue Booleans together.

More on building such conditions lives in Boolean expressions and comparison operators.


7. Functions and their ( ): print() and input()

The little round brackets ( ) are not decoration — they call a function.


8. Keywords, the colon :, and the indent

Now — and only now, with every other symbol defined — we may read a real loop:

while n > 0:      # 'while' keyword + condition + colon opens the block
    print(n)      # indented -> inside the loop, repeats
    n -= 1        # indented -> inside the loop, repeats
print("Done")     # NOT indented -> outside, runs once at the end
Figure — while loop — condition-based, infinite loop dangers

In the figure, the indented lines sit inside a coloured rectangle — that rectangle is the loop's body. The un-indented print("Done") sits outside the rectangle, so it runs only after the loop finishes. Python has no { } braces; the spaces themselves decide what is "inside." Getting the indent wrong (e.g. putting the update outside the box) is one of the parent note's classic infinite-loop bugs.


9. Two edge cases you must picture

The zero-iteration case. Because the condition is checked before the body, a while loop can run its body zero times. If the condition is already False at the very first check, Python skips the whole block and jumps to the line after it:

n = 0
while n > 0:       # 0 > 0 is False on the FIRST check
    print(n)       # never runs
print("Done")      # runs immediately

Here print(n) is never reached — the loop's body executes zero times. This is normal and often intended: "keep going if there is work, otherwise do nothing." Always ask yourself, "could my condition be false from the start?"

The infinite-loop case. The opposite danger is a condition that never turns False. It happens when the update is missing or cannot reach the boundary:

n = 5
while n > 0:       # 5 > 0 is True... and stays True forever
    print(n)       # runs again and again, no end
    # (forgot: n -= 1)

Because nothing changes n, the question n > 0 is answered True on every check — the body repeats without end and the program freezes. The cure is exactly the update line from Section 3. (In a real terminal you would press Ctrl + C to stop it.) This is the pitfall the parent note is entirely about — see break and continue statements for a controlled way to exit a loop early.


10. Putting the bricks together

Every piece of while n > 0: is now earned:

  • while — the keyword (Section 8) that says "repeat while the condition is true."
  • n — a variable, a rewritable box (Section 1) holding a number (Section 0).
  • > — a comparison operator producing a Boolean (Sections 4–5).
  • 0 — a number literal (Section 0), the value we compare against.
  • : — opens the indented body block (Section 8).
  • inside: print(n) is a function call (Section 7) that shows progress; n -= 1 is the assignment/update (Section 3) that rewrites the box using the - operator.

You can now read the parent note's countdown line by line without meeting a single unfamiliar symbol.


Prerequisite map

Read this top-to-bottom as a staircase — each row is needed by the row below it, and the whole staircase leads up to the while loop:

  1. Literals (numbers like 5, text like "5") — the raw stuff.
  2. Variables (named boxes) — where stuff is stored, built on literals.
  3. Arithmetic + - — turns one number into another.
  4. Assignment = and the update n += 1 — uses arithmetic to rewrite a box.
  5. Comparison == < > — reads boxes, asks a yes/no question.
  6. Booleans True/False — the answers comparison gives.
  7. Logical and or not — glue several Boolean answers into one.
  8. Steps 4 + 7 together form the loop's condition.
  9. Function calls ( ) (print, input) + colon/indent block — form the loop's body.
  10. while keyword binds condition + body into the loop — and forgetting the update (step 4) causes the infinite-loop danger.

if forgotten

Literals numbers and text

Variable named box

Plus and minus

Assignment and update

Comparison operators

Boolean True or False

Logical and or not

Loop condition

Function call parentheses

Loop body

Colon and indent block

while loop

infinite loop danger

Related loop tools sit in break and continue statements, the count-based sibling in for loop — iterating over sequences, and the boundary bug in Off-by-one errors.


Equipment checklist

Cover the right side. If you can answer each, you are ready for the parent note.

What is the difference between 5 and "5"?
5 is a number literal (a quantity); "5" is a string literal (text between quote-fences) — different value types.
What do quotation marks around text mean?
They mark a string literal — everything inside is treated as text, not as code.
What does = do in Python (one equals sign)?
Assignment — put the value on the right into the box (variable) on the left.
What do the + and - symbols do?
Addition and subtraction operators — each takes two numbers and produces a new number.
What does == ask (two equals signs)?
A yes/no question — "are these two values equal?" It reports True or False, changing nothing.
What is a variable, in one image?
A named box that holds one rewritable value at a time.
Read n -= 1 in three steps.
Read n, subtract 1 (the - operator), write the result back into n.
What are the only two values a Boolean can take?
True and False — nothing in between.
What does and require to be True?
Both sides must be True.
What does or require to be True?
At least one side must be True.
What does not do?
Flips a Boolean — not True is False and vice versa.
What do the parentheses ( ) after a name do?
They call a function — "run this machine now," handing it whatever is inside.
What is a keyword?
A reserved word Python already owns (like while, and, or, not); you cannot use it as a variable name.
What does the colon : plus indentation create?
A block — the indented lines form the loop body that repeats.
Does input() return a number or text?
Text (a string) always — convert with int(...) if you need a number.
Which of = or == belongs in a loop condition, and why?
== (or another comparison), because the condition must be a yes/no question, not a store command.
When does a while loop run its body zero times?
When its condition is already False at the very first (pre-test) check.
What makes a loop infinite?
A condition that never becomes False — usually a missing or unreachable update.