1

Here is the code all_jokes is a dictionary that has some categories mapped to jokes.

def select_joke(category):
    jokes = all_jokes[category or 'default']
    shuffle(jokes)
    return jokes[0]
Phoenix
  • 3,996
  • 4
  • 29
  • 40
Rahul Nanda
  • 37
  • 1
  • 6

4 Answers4

3

Returns the value of the default key in the all_jokes dict if the value of category wasn't truthy:

from random import shuffle

all_jokes = {
    'joke1': ['This is joke1'],
    'joke2': ['This is joke2'],
    'default': ['This is default joke']
}

def select_joke(category):
    jokes = all_jokes[category or 'default']
    shuffle(jokes)
    return jokes[0]

print("----------------------------------------")
print(f"input:{0} output:{select_joke(0)}")
print(f"input:{None} output:{select_joke(None)}")
print(f"input:{''} output:{select_joke('')}")
print("----------------------------------------")

Output:

----------------------------------------
input:0 output:This is default joke
input:None output:This is default joke
input: output:This is default joke
----------------------------------------
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Phoenix
  • 3,996
  • 4
  • 29
  • 40
0

As in many other languages, or returns the first element if it's "truthy", the second one otherwise.

In this case, if category is 0, or None, or the empty string, etc., we get all_jokes['default']. Otherwise, we get all_jokes[category].

L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

It means,

if category is false (or empty or None) use 'default' as key.

Probably without knowing the rest of the code, all_jokes is a dictionary which contains a default option.

Phoenix
  • 3,996
  • 4
  • 29
  • 40
mrzo
  • 2,002
  • 1
  • 14
  • 26
0

Python's and and or operators are equivalent to the following if expressions:

# NB: These work as intended for boolean values.
(a or b) is (a if a else b)
(a and b) is (b if a else a)
def select_joke(category):
    """Equivalent to your code."""
    jokes = all_jokes[category if category else 'default']
    shuffle(jokes)
    return jokes[0]

This allows call sites which are fine accepting 'default' jokes to pass in '' or None. Python code tends to look more beautiful when or is used in place of if expressions which match this pattern (replacing a falsy value with another), especially if you use function arguments which default to a falsy value.


As a side note, you can simplify your function with random.choice:

def select_joke(category=None):
    return random.choice(all_jokes[category or 'default'])


select_joke()          # category will be 'default'.
select_joke('default') # category will be 'default'.
select_joke(None)      # category will be 'default'.
select_joke('')        # category will be 'default'.
select_joke('puns')    # category will be 'puns'.
Brian Rodriguez
  • 4,250
  • 1
  • 16
  • 37