Sub topic 2
Combining Conditions with `and`, `or`, `not`
Assume you know Python variables, functions, if statements, and basic types such as strings, lists, and dictionaries.
Combining conditions with `and`, `or`, and `not`
Python uses three Boolean operators:
andrequires both operands to be truthy.orrequires at least one operand to be truthy.notreverses a truth value.
age = twenty = 20
has_ticket = True
if age >= 18 and has_ticket:
print("You may enter")
if age < 18 or not has_ticket:
print("Entry denied")An object is truthy when Python treats it as true in a condition. Empty containers, empty strings, 0, 0.0, and None are falsy.
Short-circuiting and returned values
and and or stop as soon as the final result is known. This is called short-circuit evaluation.
a and breturnsaifais falsy; otherwise it returnsb.a or breturnsaifais truthy; otherwise it returnsb.
They return an operand, not necessarily True or False.
username = ""
display_name = username or "anonymous"
print(display_name) # anonymous
items = []
first = items and items[0]
print(first) # []
print("ready" and 42) # 42The second expression safely avoids indexing an empty list because items[0] is never evaluated.
`None`: absence of a value
None is Python's singleton value meaning “no value” or “not provided.” Use is None to test for it.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("tea")) # ["tea"]
print(add_item("milk")) # ["milk"]Using None as the default avoids sharing one mutable list between calls.
`is` versus `==`
== tests equality: whether two objects have equivalent values. is tests identity: whether two names refer to the same object.
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
result = None
if result is not None:
print("A result exists")Use is and is not for None. Use == when comparing ordinary values.
Exercise
What does [] or "backup" return, and why does items and items[0] avoid an error when items is empty?
Show answer
It returns "backup" because an empty list is falsy. The and expression stops at the empty list, so it never evaluates items[0].