I am trying to make a menu of options in python where if the user selects a number a different function is executed:
def options(x):
return {
1: f1(),
2: f2()
}[x]
def f1():
print "hi"
def f2():
print "bye"
However, well I call
options(1)
I get:
hi
bye
and same when I call options(2)
What is going on?
You are invoking the functions instead of assiging them against the keys
def f1():
print "hi"
def f2():
print "bye"
functions = {1: f1, 2: f2} # dict of functions (Note: no parenthesis)
def options(x):
return functions[x]() # Get the function against the index and invoke it
options(1)
# hi
options(2)
# bye
Your dictionary is built with the return values of the functions; don't call the function until after picking it from the dict:
def options(x):
return {
1: f1,
2: f2
}[x]()
Now you are storing just a reference to the functions in the dictionary, and call the selected function after retrieving it.
Demo:
>>> def f1():
... print "hi"
...
>>> def f2():
... print "bye"
...
>>> def options(x):
... return {
... 1: f1,
... 2: f2
... }[x]()
...
>>> options(1)
hi
>>> options(2)
bye
Replace print with return and return with, then it will work. Or use thefourtheye version.
The problem is that you call the functions (with ()
) while you are building the dictionary. Leave the parens off and apply them later only after getting the value from the dictionary:
def options(x):
return {
1: f1,
2: f2
}[x]()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.