Truthiness
Python can treat any value as True or False. A value that counts as False is called falsy, and one that counts as True is truthy. Empty values and zero are falsy:
| Falsy value | Truthy values |
|---|---|
False | True |
0 or 0.0 | Non-zero numbers, including negative ones |
"" | Non-empty strings |
Lists and other containers, which you will meet later, follow the same rule. An empty one is falsy. To see whether any value is truthy or falsy, pass it to bool():
name = ""
count = 3
print(bool(name))
print(bool(count))
print(bool("0"))
print(name or "guest")
Output:
False
True
True
guest
The string "0" is truthy, even though the number 0 is falsy. The string is not empty, because it contains one character.
or gives back the first truthy value it finds. If no value is truthy, it gives back the last one, so 0 or "" gives "". Here name is empty, so name or "guest" gives "guest". This makes or useful for a default, which is a value to use when nothing else is given. Truthiness also decides how if conditions behave. You will learn if in the next section.
In the exercise, use bool and or on the text and the number you are given.