Yax Yax - 1 month ago 6
Python Question

Shortest way to run seven if statements in Python

I have an

if
statements that checks a number and then return a string value accordingly.

code:

def get_weekday(day):
if day in ['1', 1]:
return 'Monday'
elif day in ['2', 2]:
return 'Tuesday'
elif day in ['3', 3]:
return 'Wednesday'
elif day in ['4', 4]:
return 'Thursday'
elif day in ['5', 5]:
return 'Friday'
elif day in ['6', 6]:
return 'Saturday'
elif day in ['7', 7]:
return 'Sunday'
return 'Invalid day selected'


The question may appear subjective but I think there should be a pythonic and better and shorter and cleaner way of writing this.

Answer

What I would do instead, is create a dictionary, and cast your day to a single type, and then look that up in your dictionary. This significantly minimizes your code:

def get_weekday(day):
    days_dict = {
        '1': 'Monday',
        '2': 'Tuesday',
        '3': 'Wednesday',
        '4': 'Thursday',
        '5': 'Friday',
        '6': 'Saturday',
        '7': 'Sunday'
    }
    return days_dict.get(str(day), 'Invalid day selected')

So, what is happening in the above function, is you are passing your day, it doesn't matter whether you pass it as a string or an int, the casting is made as an str already. Your dictionary now holds the mapping for you, and lookup will cost you O(1).

The get method will return None if it does not find an entry in your dictionary. However, per your requirement, you are looking to return Invalid day selected for invalid entries. get will take an extra argument that will be returned in the event an invalid key is provided.

Here is a demo of the different cases that can come up and how the function behaves:

>>> print(get_weekday(2))
Tuesday
>>> print(get_weekday('5'))
Friday
>>> print(get_weekday("invalid_thing"))
Invalid day selected