Booleans and truthiness
The bool type has exactly two values: True and False (capital first letter, no quotes). Every comparison produces one of them.
Python
is_raining = True
has_umbrella = False
print(is_raining, type(is_raining))
print(5 > 3)Booleans are numbers in disguise
True behaves like 1 and False like 0. That makes counting easy:
Python
print(True + True + False)
answers = [True, False, True, True]
print("Correct answers:", sum(answers))Truthy and falsy
In an if or while, Python accepts any value, not just booleans. It treats some values as false (falsy) and everything else as true (truthy).
Falsy values:
FalseandNone- zero:
0,0.0 - empty collections:
"",[],(),{},set()
Python
name = ""
if name:
print("Hello,", name)
else:
print("No name given")
cart = ["apple"]
if cart:
print("You have", len(cart), "item(s)")Writing if cart: instead of if len(cart) > 0: is the Pythonic way to ask "is this non-empty?".
and / or return a value
This surprises many people: and and or don't always return True/False. They return one of their operands:
a or breturnsaifais truthy, otherwiseba and breturnsaifais falsy, otherwiseb
Python
print("" or "default")
print("Asha" or "default")
print(0 and 99)
print(5 and 99)This gives a neat way to provide default values:
Python
user_input = ""
name = user_input or "Guest"
print("Welcome,", name)Comparing with None
To check for None, use is, not ==:
Python
result = None
print(result is None)
print(result is not None)is checks whether two names refer to the very same object, and there is only ever one None.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.