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>A generic solution would be:</p>

<pre><code>def get_day_name(day):
    return {
        '1': 'Monday',
        '2': 'Tuesday',
        '3': 'Wednesday',
        '4': 'Thursday',
        '5': 'Friday',
        '6': 'Saturday',
        '7': 'Sunday'
    }.get(str(day), 'Invalid day selected')
</code></pre>

<p>Several things are done here:</p>

<ol>
<li>to get rid of checking both strings <code>'2'</code> and integers <code>2</code>, convert all to strings: <code>str(day)</code></li>
<li>there is a mapping (<code>dict</code>) from all allowed strings (<code>'1'</code> - <code>'7'</code>) to the results</li>
<li>instead of just taking the result with <code>{...}[day]</code>, dictionary provides methog <code>get</code> which accepts the <em>default</em> argument to be returned if the key is not found (<code>'Invalid day selected'</code>).</li>
</ol>

<hr>

<p>But then again, since those are just numbers, this can be simplified using a list instead of a dictionary:</p>

<pre><code>def get_day_name(day):
    day = int(day)
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

    if 1 &lt;= day &lt;= 7:
        return days[day-1]
    else:
        return 'Invalid day selected'
</code></pre>

<p>In this case, strings are first converted to integers and then the integers are used to get a value from the list.
This, of course, won't work if <code>day = 'something that isnt int'</code>. This would raise an exception which could be handled, but if that has to be handled, the solution with dict is nicer.</p>

python