Alg_D
Alg_D

Reputation: 2390

python - pass argument to function in a dictionary

I've something like a switch, that given an option will call a function e.g.

#... capture option
op = getOption()
#.. capture metric
mt = getMetric()

def zipcode():
    print "You typed zero.\n"
def desc():
    print "n is a perfect square\n"
def address():
    print "n is an even number\n"

#call desired option
options= {0 : zipcode,
          1 : code,
          2 : desc,
          3 : address
}

options[op]()

I am trying to pass a parameter (mt) into my options dict that will call a function, but i'm not being able to do so.

if op received is 1 and mt is foo, how the call to the right function (zipcode) will be done by passing mt as a parameter?

ideally: options[op](mt) and defining one parameter in the function?

Thanks

Upvotes: 2

Views: 2547

Answers (1)

user764357
user764357

Reputation:

Your code is not indented properly, which is very important in Python and would cause syntax errors as is.

However, what you are suggesting would work perfectly.

Consider the following:

def multiply(m,n):
    return n*n

def add(m,n)
    return m,n

my_math = { "+":add,
            "*":multiply}

You could then call that as follows:

>>> print my_math["+"](1,2)
3
>>> print my_math["*"](4,5)
20

Upvotes: 4

Related Questions