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]
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]
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
----------------------------------------
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]
.
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'.