About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Sunday, June 7, 2020

Python Trick: Alternative to if-else/Case statement

Lets look the below code snippet

def add_number(a,b):
   
print(a+b);

def multiply_number(a,b):
   
print(a*b)

def division_number(a,b):
   
print(a/b)

result =
'30'

if result == '10':
    add_number(
10,20)
elif result == '20':
    multiply_number(
12,2)
elif result== '30':
    division_number(
36,3)


here we have three method, and methods are called depending upon the value of result, if the result value is 10 then add_number is called, if result is 20 then multiply_number is called and so on

So you can see above we have written multiline if-elseif statement to call method on the bases of result value.

Now lets see the below code snippet, here we have declare a dictionary object with result value as a key of dictionary object and the associated method as a dictionary key value.

result_dict={
   
'10':add_number,
   
'20':multiply_number,
   
'30':division_number
}

result=
'10'
result_dict[result](1,2)

The result value is store in a result variable and that variable is passed as an index to dictionary key which internally calls the associated method. So it just one line statement instead of if-else ladder.


Enjoy pythonic way J

Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment