Python Booleans: Truthy and Falsy Values
In Python, every value is truthy or falsy: if treats it as True
or False, even when it is not a boolean.
Read Comparisons and Logical Operators first.
Which values are falsy
bool() shows how if will treat a value.
print(bool(0), bool(0.0), bool(""), bool([]), bool({}), bool(None))
print(bool(7), bool(-1), bool("hi"), bool(" "), bool([0]))
The first line is all False: zero, empty text, empty lists and
dictionaries, and None. The second is all True. A space and a list
holding 0 are not empty, so they are truthy.
Test for empty without len()
Because empty values are falsy, if items: means "if items is not empty".
name = ""
if not name:
print("Please type a name")
items = ["key"]
if items:
print("You are carrying", len(items), "item")
This is the same as len(name) == 0 and len(items) > 0, written shorter.
Use the long form when 0 and empty must be treated differently, for
example a score that may really be 0.
Why choice == 1 or 2 is always true
or does not repeat the comparison. Python reads choice == 1 or 2 as
(choice == 1) or 2.
choice = 5
print(choice == 1 or 2)
if choice == 1 or 2:
print("this always runs")
print(choice == 1 or choice == 2)
print(choice in (1, 2))
The first line prints 2, which is truthy, so the if always runs. The
last two lines are correct and print False.
and and or return one of their values
or returns the first truthy value, or the last value if none is truthy.
and returns the first falsy value, or the last value if all are truthy.
print("" or "Guest")
print("Ada" or "Guest")
print(0 and 10)
print(3 and 10)
This prints Guest, Ada, 0, then 10. So typed or "Guest" gives a
default for empty text. Both operators also short-circuit: they stop
as soon as the answer is known, so the right side may never run.
items = []
print(len(items) > 0 and items[0] == "key")
This prints False with no IndexError: items[0] is never evaluated.
Note: the default trick replaces every falsy value. 0 or 10 gives
10, so do not use it when 0 is a valid answer.
See also: Data Validation, Membership Testing.
Your turn
For each value in typed, print the name to use: the value itself, or
"Guest" when it is empty. Then print whether the list typed is non-empty
using bool().
typed = ["Ada", "", "Sam"]
for value in typed:
# print value, or "Guest" when it is empty, using or
pass
# print whether typed is non-empty
Expected output
Ada
Guest
Sam
True