Legends ofPythos
Claim your name
Working with Data

Conditions in depth

Lesson 3 of 14

Watch the lesson1:26 · with Torsten
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')
Checks if a number falls within a range

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.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Write grade(score). It returns 'invalid' when score is None (test for that with is None) or is outside 0 to 100, 'pass' for a score from 50 to 100, and 'fail' for a score from 0 up to but not including 50. Use chained comparisons such as 50 <= score <= 100. For example, grade(72) is 'pass'.
def grade(score):
    # None first, then the ranges with chained comparisons
    pass

Run your code to check it against the tests.

Exercise 2

+30 XP
Write greeting(profile), where profile is a dictionary. The name is the value of its 'name' key if that value is truthy, and 'Guest' otherwise, including when the key is missing (or can supply the default). The greeting is f'Welcome, {name}', and if the profile has a non-empty 'tags' list, add f' ({n} tags)' where n is how many there are. For example, greeting({'name': 'Linus', 'tags': ['admin', 'ops']}) is 'Welcome, Linus (2 tags)'.
def greeting(profile):
    # A truthy name or 'Guest', then the tag count if there are any tags
    pass

Run your code to check it against the tests.

Exercise 3

+30 XP
Tuples compare item by item from the left, which makes them handy for ranking. Write better(a, b), where each argument is a race result (points, time): more points wins, and when the points are equal the lower time wins. Return 'a', 'b' or 'tie'. Turning each result into (points, -time) lets one tuple comparison do the ranking. For example, better((10, 50), (10, 45)) is 'b'.
def better(a, b):
    # Rank each result as a tuple, then compare the tuples
    pass

Run your code to check it against the tests.