Switch Statement in Python

There is no keyword as switch in python. But there is easy and pythonic way to write switch statement in python.

let say you have function which accept different parameter and take different actions on that example:

def calculate(first_num, second_num, method):
    if method == 'add':
        return first_num + second_num
    elif method == 'minus':
        return first_num - second_num
    elif method == 'divide':
        return first_num//second_num
    elif method == 'multiply':
        return first_num * second_num
    else:
        return 'Wrong Input'

We can convert this into dictionary and create multiple individual functions or lambda functions as:

def calculate(first_num, second_num, method):
    cal_methods = {'add': lambda first, second: first + second,
                   'minus': lambda first, second: first - second,
                   'divide': lambda first, second: first // second,
                   'multiply' lambda first, second: first * second }
    if method in cal_methods:
        return cal_methods[method](first_num, second_num)
    return 'Wrong Input'

OR you can write functions like:

def add(first, second):
    return first + second

def minus(first, second):
    return first - second

--similarly other function..

Now you can access these function similar as above:

 if method in cal_methods:
        return cal_methods[method](first_num, second_num)
    return 'Wrong Input'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: