Shortest way to run seven if statements in Python
<p>I have an <code>if</code> statements that checks a number and then return a string value accordingly.</p>

<p><strong>code:</strong></p>

<pre><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'
</code></pre>

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

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

<pre><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')
</code></pre>

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

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

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

<pre><code>&gt;&gt;&gt; print(get_weekday(2))
Tuesday
&gt;&gt;&gt; print(get_weekday('5'))
Friday
&gt;&gt;&gt; print(get_weekday("invalid_thing"))
Invalid day selected
</code></pre>

python