Sub topic 2
What counts as a true condition
A while loop asks one question before every pass: is the condition true? This chapter covers how Python answers that question. It assumes you can write a basic while loop, use comparison operators (==, <, !=) and boolean operators (and, or, not), and read if statements. The key point is that the condition does not have to be a comparison. Any Python object can serve as a condition, and knowing which objects count as true prevents several subtle bugs.
The condition is evaluated before every pass
Python evaluates the condition once before the first pass and again after each pass finishes. If the result is true, the body runs. If it is false, the loop ends and execution continues after the loop.
The condition is an ordinary expression that is recomputed each time. If it calls a function, the function is called on every check. If it reads a variable, it sees the variable's current value.
Truthiness: every object has a boolean value
Python converts the condition's result to a boolean using the object's truth value. Objects that convert to False are called falsy. Objects that convert to True are called truthy. The built-in bool() function shows the conversion directly.
values = [0, 1, -1, 0.0, 0.1, "", " ", "0", [], [0], {}, (), None, False]
for v in values:
print(f"{v!r:>6} -> {bool(v)}")The rule for built-in types is short. A value is falsy if it is a zero number, an empty collection or string, None, or False. Every other value is truthy.
| Type | Falsy values | Truthy examples |
|---|---|---|
| Numbers | `0`, `0.0`, `0j` | `1`, `-1`, `0.1` |
| Strings | `""` | `" "`, `"0"`, `"False"` |
| Lists, tuples | `[]`, `()` | `[0]`, `(None,)` |
| Dicts, sets | `{}`, `set()` | `{"a": 0}`, `{0}` |
| Other | `None`, `False`, `range(0)` | any function, any class instance by default |
Two entries in the truthy column often surprise people. The string "0" is truthy because it is a non-empty string, not a number. A list containing only falsy items, such as [0], is also truthy, because the list itself is not empty.
Where truthiness comes from
For your own classes, Python checks two special methods in order:
- If the class defines
__bool__, Python calls it and uses the returnedTrueorFalse. - Otherwise, if the class defines
__len__, the object is falsy when the length is0. - If neither method exists, the object is always truthy.
This is why empty lists and strings are falsy: they define a length of zero. The following class makes the repeated evaluation visible by printing a message each time Python checks the condition.
class Countdown:
def __init__(self, n):
self.n = n
def __bool__(self):
print(" checking condition")
return self.n > 0
c = Countdown(2)
while c:
print("body, n =", c.n)
c.n -= 1
print("finished")The output shows three checks for two passes: one before each pass, and one final check that fails.
Using truthiness as a loop condition
Because collections are falsy when empty, a collection can be its own loop condition. This pattern appears often when you process a work list that shrinks as you go.
tasks = ["write", "test", "ship"]
while tasks:
task = tasks.pop(0)
print("doing", task)
print("no tasks left")while tasks: reads as "while there are still tasks". The body removes one item per pass, so the list eventually becomes empty and the condition turns falsy. This also shows why the loop terminates: the body changes the thing the condition inspects.
The explicit form is while len(tasks) > 0:. It does the same thing. Most Python style guides prefer while tasks:, but the explicit form is acceptable when it makes the intent clearer to the reader.
Comparisons always produce a bool
Comparison operators such as <, ==, in, and is return True or False. Python also allows chained comparisons, which are evaluated as a combined test.
n = 5
while 0 < n <= 8:
print(n)
n += 1This prints 5, 6, 7, 8. The chain 0 < n <= 8 means 0 < n and n <= 8, with n evaluated once. It is both shorter and less error-prone than writing the two tests separately.
`and`, `or`, and `not` in conditions
The operator not always returns a real boolean. The operators and and or do not. They return one of their operands, and they stop evaluating as soon as the result is known (this is called short-circuiting).
print(0 or "default") # default
print("a" and "b") # b
print([] and 5) # []
print(None or []) # []The rules are:
x or yreturnsxifxis truthy, otherwisey.x and yreturnsxifxis falsy, otherwisey.
The while statement only cares whether the final result is truthy, so this behavior rarely changes whether a loop runs. Short-circuiting does matter for safety, though. In the next loop, the index check comes first and protects the second part.
items = [4, 8, 15]
i = 0
while i < len(items) and items[i] != 15:
i += 1
print("found at index", i)If the two tests were swapped, items[i] would raise an IndexError once i reached 3. With the order shown, the second test is skipped when i < len(items) is false.
Common condition mistakes
Mistake 1: `or` with a bare value
A frequent error is to treat or like English:
answer = "no"
print(answer == "y" or "yes") # yesPython reads this as (answer == "y") or "yes". The left side is False, so the result is the string "yes", which is truthy. A loop written as while answer == "y" or "yes": would therefore never end, whatever the user typed. The correct forms are:
answer = "no"
print(answer in ("y", "yes")) # False
print(answer == "y" or answer == "yes") # FalseFor a loop that continues until the user agrees, use while answer not in ("y", "yes"):.
Mistake 2: relying on text from `input`
input() always returns a string, and any non-empty string is truthy. This loop stops only when the user presses Enter on an empty line:
replies = iter(["0", "no", "", "later"]) # stands in for typed input
while reply := next(replies):
print("got", repr(reply))
print("stopped")This prints got '0' and got 'no', then stops at the empty string. The text "0" and "no" look like "off" to a human, but Python treats them as truthy. Compare the text explicitly, or convert it with int() first, if you want a different rule.
The walrus operator := assigns a value and returns it in one expression. A later chapter covers it in detail. Here it only lets the condition both read and test the next reply.
Mistake 3: a valid value that is falsy
Truthiness tests ask "is this empty or zero?", which is different from "is this missing?". When zero or an empty string is a legitimate value, a bare truthiness test ends the loop too early.
readings = iter([5, 3, 0, 8])
while (r := next(readings, None)) is not None:
print(r)This prints 5, 3, 0, 8. The condition compares against None with is not None, so the legitimate reading 0 does not stop the loop. If you wrote while r := next(readings, None):, the loop would end at 0 and silently skip 8.
Mistake 4: comparing floats for equality
Floating-point numbers are stored in binary, so many decimal fractions are not exact.
x = 0.0
for _ in range(10):
x += 0.1
print(x, x == 1.0) # 0.9999999999999999 FalseA loop such as while x != 1.0: that adds 0.1 each time never sees exactly 1.0, so the condition stays true forever. Use an ordering comparison (while x < 1.0:), or count whole steps with an integer and compute the float from it. If you must test closeness, math.isclose(x, 1.0) allows a small tolerance.
Mistake 5: truthiness of array-like objects
Some library types do not follow the empty-or-zero rule. A NumPy array with more than one element raises a ValueError when you use it as a condition, because "is this array true?" is ambiguous. In loops over such objects, use an explicit test such as arr.size > 0 or arr.any().
Writing conditions that read well
A few habits keep conditions correct and easy to check:
- Name boolean variables so the condition reads as a sentence:
while not finished:orwhile has_more_pages:. - Do not compare to booleans with
== Trueor== False. Writewhile flag:orwhile not flag:. - Use
is Noneandis not Nonefor missing values, never== None. - Put the cheap or protective test first in an
andchain, as in the index example above. - Keep conditions short. If one grows past two or three parts, assign pieces to named variables inside the loop, or move them into a small function.
What the condition cannot do alone
A correct truthiness test only decides whether the next pass runs. It does not guarantee that the condition ever becomes false. That depends on the body changing the values the condition reads, which is the subject of the next chapter. A test such as while tasks: terminates only because tasks.pop(0) shrinks the list. If the body forgot to remove items, the condition would stay truthy forever.
Exercise
Predict the output of this program, and explain why the loop stops where it does. items = ["a", "", "c", "d"] i = 0 while i < len(items) and items[i]: print(items[i]) i += 1 print("i =", i)
Show answer
It prints a, then i = 1. On the second check, i < len(items) is true, so Python evaluates items[1], which is the empty string "". An empty string is falsy, so the whole and expression is falsy and the loop ends before c and d are reached. The loop stops on a falsy element, not at the end of the list.
Exercise
A program reads sensor values from an iterator and must process every value, including 0. Which condition is correct, while value := next(sensor, None): or while (value := next(sensor, None)) is not None:? Why?
Show answer
The second one. The first condition is a bare truthiness test, so a legitimate reading of 0 is falsy and ends the loop early, skipping later values. The second compares with None, which is the only value that means "no more data", so 0 is processed like any other reading.