switch case in python

Python does not have a built-in switch case statement like some other programming languages. However, we can achieve similar functionality using conditional statements. Here is an example:

main.py
def switch_case(argument):
    switcher = {
        1: "January",
        2: "February",
        3: "March",
        4: "April",
        5: "May",
        6: "June",
        7: "July",
        8: "August",
        9: "September",
        10: "October",
        11: "November",
        12: "December"   
    }

    return switcher.get(argument, "Invalid month")
361 chars
18 lines

In the above code snippet, we have defined a switcher dictionary that maps the cases to their corresponding values. We then call switcher.get(argument, "Invalid month") to get the corresponding value for the given argument.

Here is an example usage:

main.py
month_number = 4
print(switch_case(month_number))  # Output: "April"

invalid_month_number = 13
print(switch_case(invalid_month_number))  # Output: "Invalid month"
164 chars
6 lines

Note that the second argument to get() (i.e., "Invalid month") is the default value returned if the argument is not found in the switcher dictionary.

gistlibby LogSnag