Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the program choose between two function in python?

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?

like image 757
Scipio Avatar asked Dec 16 '22 15:12

Scipio


2 Answers

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.

like image 165
Martijn Pieters Avatar answered Dec 21 '22 09:12

Martijn Pieters


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)
>>>
like image 27
Abhijit Avatar answered Dec 21 '22 09:12

Abhijit