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.
defa():
return2 + 3defb():
return3 - 2defc():
return2*3defd():
return2/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 = 0for i infuncs:
result += dic[i]()
print result
Solution 2:
You can use getattr() to get the functions:
import sys
defa():
return1defb():
return2defc():
return3sum = 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"