I've got a Python 3.2 program that computes the value of an investment carried any amount of time periods into the future, it may work with both simple and compound interest. The thing is that I've got two functions defined, "main()" and "main2()", the first is for simple and the second is for compound interest. Now what I want to do is that given some input from the user the program chooses between running main() or main2(). Any ideas on how to do this?
First of all, give your functions better names. Then use a mapping:
def calculate_compound(arg1, arg2):
# calculate compound interest
def calculate_simple(arg1, arg2):
# calculate simple interest
functions = {
'compound': calculate_compound,
'simple': calculate_simple
}
interest = functions[userchoice](inputvalue1, inputvalue2)
Because Python functions are first-class citizens you can store them in a python dictionary, use a key to look them up, then call them.
You can use the solution as poster by Martijn, but you can also use the if/else
Python construct to call either your simple
or compound
calculate routine
Considering the fact the Compound Interest routine should take an additional paramenter n
, the freq of interest calculation, so based on the parameter length you can switch the function calls.
Also your driver routine should accept variable arguments to accept the arguments for both types of functions
>>> def calc(*args):
if len(args) == 3:
return calc_simple(*args)
elif len(args) == 4:
return calc_compund(*args)
else:
raise TypeError("calc takes 3 or 4 arguments ({} given)".format(len(args)))
>>> def calc_compund(*args):
P, r, n, t = args
print "calc_compund"
#Your Calc Goes here
>>> def calc_simple(*args):
P, r, t = args
print "calc_simple"
#Your Calc Goes here
>>> calc(100,10,2,5)
calc_compund
>>> calc(100,10,5)
calc_simple
>>> calc(100,10)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
calc(100,10)
File "<pyshell#101>", line 7, in calc
raise TypeError("calc takes 3 or 4 arguments ({} given)".format(len(args)))
TypeError: calc takes 3 or 4 arguments (2 given)
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With