Optional Function To Choose For User
I wrote a program using many functions (def name():). These function are summed at the end of code like: a()+b()+c()+d()+e() In what way I can do this: program: >>>a,b,c,d
Solution 1:
You could use a dictionary in the following way.
def a():
return 2 + 3
def b():
return 3 - 2
def c():
return 2*3
def d():
return 2/3
dic = {}
dic['a'] = a
dic['b'] = b
dic['c'] = c
dic['d'] = d
funcs = str(raw_input("which functions would you like to use?: "))
funcs = funcs.split(',')
result = 0
for i in funcs:
result += dic[i]()
print result
Solution 2:
You can use getattr() to get the functions:
import sys
def a():
return 1
def b():
return 2
def c():
return 3
sum = 0
# Assume user input of 'a' & 'c'
for name in ['a', 'c']:
#
# Get the function and call it...
#
sum += getattr(sys.modules[__name__], name)()
print('sum: {}'.format(sum))
Post a Comment for "Optional Function To Choose For User"