Sub topic 2
What counts as a true condition
This chapter assumes you know variables, comparison operators (==, <, >=), the boolean operators and, or, not, and how an if statement works. It covers what Python accepts as a loop condition and what it does with the value you give it.
A condition is any expression
A while loop does not require a comparison. Python evaluates the expression after while, converts the result to a boolean, and runs the body only if that boolean is True. The conversion is called truth testing, and it applies to every object.
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff")Here n > 0 produces a real bool. The same rule works for values that are not booleans, such as numbers, strings, and lists.
Truthy and falsy values
A value is falsy if Python treats it as false in a condition. A value is truthy if Python treats it as true. Only a small set of values is falsy. Everything else is truthy.
| Value | Type | Truth value |
|---|---|---|
| `False` | bool | falsy |
| `None` | NoneType | falsy |
| `0`, `0.0` | int, float | falsy |
| `""` | str | falsy |
| `[]`, `()`, `{}`, `set()` | empty containers | falsy |
| `-1`, `0.1` | numbers | truthy |
| `"0"`, `" "`, `"False"` | non-empty strings | truthy |
| `[0]`, `[None]` | non-empty lists | truthy |
Note that "0" is truthy. It is a string with one character, and only the empty string is falsy. A list containing 0 is also truthy, because the list is not empty.
You can check any value with the built-in bool() function.
for value in [0, 1, "", "0", [], [0], None]:
print(repr(value), bool(value))The output is:
0 False
1 True
'' False
'0' True
[] False
[0] True
None FalseUsing truthiness to drive a loop
Truthiness lets a loop test "is there anything left?" directly. This loop empties a list and stops when the list becomes empty.
tasks = ["email", "report", "review"]
while tasks:
current = tasks.pop()
print("Working on", current)
print("All done")The condition tasks is truthy while the list has items. After the third pop(), the list is [], which is falsy, and the loop ends. The state update here is the pop() call, so the loop still moves toward ending.
This is shorter than while len(tasks) > 0: and is the usual style in Python. Use the explicit form when it makes the intent clearer to a reader.
How the condition is evaluated
The following diagram shows the cycle. The condition is checked before every pass, including the first one. If it is false on the first check, the body never runs.
Combining conditions with and, or, not
The operators and and or do not always return True or False. They return one of their operands, and they stop evaluating as soon as the result is known. This is called short-circuit evaluation. In a loop condition, the returned operand is then tested for truth like any other value.
items = []
i = 0
while i < len(items) and items[i] != "stop":
i += 1
print("Stopped at index", i)Because i < len(items) is false for an empty list, Python never evaluates items[i]. Without the short-circuit, that expression would raise an IndexError. Put the cheap or safety-checking test first.
Common errors
- Testing the wrong thing.
while "False":loops forever, because the string"False"is non-empty and therefore truthy. Convert text to a real value before testing it. - Confusing
Nonewith zero. A function that returns0and one that returnsNoneare both falsy, but they mean different things. If0is a valid result, testis not Noneinstead of relying on truthiness. - Using
isor==with booleans needlessly. Writingwhile running == True:works, butwhile running:is the standard form. - Forgetting that the condition must change. A truthy condition that nothing modifies never ends. The next chapters cover this in detail.
Exercise
What does this code print, and why? data = [0] count = 0 while data and count < 5: count += 1 print(count)
Show answer
It prints 5. The list [0] is not empty, so data is truthy even though it holds a falsy value. Nothing changes data, so the first part of the condition stays true. The loop ends only when count < 5 becomes false, which happens when count reaches 5.
Exercise
Rewrite while len(queue) != 0: in the more idiomatic form, and name one situation where you would keep the original.
Show answer
Use while queue:. You might keep the original when queue could be a type that does not follow the usual truthiness rule, or when a reader benefits from seeing the length check stated outright.