Search code examples
pythonpython-3.xdictionarybinary-operators

What is the need of 'or default' in this python code?


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]

Solution

  • 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
    ----------------------------------------