You already know how to check if a value is greater than or less than another. Python lets you chain these comparisons together, just like reading math notation.
Chained Comparisons
score = 85
if 0 <= score <= 100:
print('Valid')
elif score < 0:
print('Negative')
else:
print('Too high')is, in and not in
== checks if two values are equal. is checks if they are the exact same object in memory. For most data, use ==. The one exception is checking for None, where you should always write x is None or x is not None.# Using 'in' to check membership
fruits = ['apple', 'banana']
if 'apple' in fruits:
print('Found it')
# Checking dictionary keys
user = {'name': 'Alice'}
if 'email' not in user:
print('No email provided')Truthiness and Short-Circuiting
Some values are naturally 'falsy' (false in a boolean context):
0, '' (empty string), [] (empty list), {} (empty dict), and None. This means you can check if something is empty without using len().# Truthiness: 'if items' checks if the list is NOT empty
items = []
if items:
print('There are things')
else:
print('Empty')Short-circuit evaluation saves you from doing unnecessary work.
and stops at the first falsy value; or stops at the first truthy one. This is how we often provide default values.# Supplying a default with 'or'
name = None
display_name = name or 'Guest'
print(display_name) # Prints: Guest
# Comparing sequences (tuples/lists)
a = [1, 2]
b = [1, 3]
if a < b:
print('a comes first')Comparing sequences
Lists and tuples compare item by item from the left. The first pair of items that differ decides the answer, so
[1, 2] < [1, 3] is True because 2 < 3, and (2, 'b') < (2, 'c') is True because the first items tie and 'b' comes before 'c'. If one runs out first, the shorter one is smaller: [1, 2] < [1, 2, 0] is True.