Sub topic 1
Python `while` Loops, `break`, and `continue`
Prerequisites
You should know variables and assignment, comparison and Boolean operators, if statements, indentation, and basic use of print() and input().
How a `while` Loop Works
A while loop repeats a block while its condition is true. Python checks the condition before every iteration. If the condition is false initially, the body runs zero times.
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff")The output is 3, 2, 1, and then Liftoff. The assignment n -= 1 changes the loop's state, meaning the values that control its future behavior.
What Counts as a True Condition
Python evaluates any expression in a condition using truthiness. A truthy value acts like True; a falsy value acts like False.
Common falsy values include False, None, 0, 0.0, and empty strings, lists, tuples, dictionaries, and sets. Most other values are truthy.
items = ["red", "blue", "green"]
while items:
print(items.pop())The list is truthy while it contains elements. After pop() removes the last element, the list eventually becomes empty and therefore falsy.
Changing State So the Loop Can End
A terminating loop needs a condition and a state update that move toward the condition becoming false. Check that the update happens on every path through the body.
For example, forgetting n -= 1 in the first example creates an infinite loop. An infinite loop never reaches a false condition and keeps running until an external action stops it.
Infinite Loops and `while True`
while True deliberately creates a loop whose condition never becomes false. Use it when the stopping rule is an event inside the body. The break statement exits the loop immediately.
while True:
answer = input("Type quit to stop: ")
if answer == "quit":
break
print("You typed:", answer)Use this pattern only when the body clearly contains a reachable stopping event. Otherwise, prefer a condition that shows termination directly.
Exercise
Why does while count < 3 become infinite if the loop body never changes count?
Show answer
The condition stays true because count never moves toward 3, so Python repeats the body indefinitely.