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)
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)
'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