Reputation: 21
I am trying to create a simple menu by utilizing a dictionary instead of a series of if, elif statements. My problem is the functions being called when I declare them as the definition within the dictionary. Also I'm running into an error when trying to call on the dictionary.
I know that I'm missing something with the declaration. It doesn't matter what I put in the definition, if it's executable code then it executes when declared instead of when I call on it.
As far as the problem with calling on the dictionary I'm totally lost, from everything I've read I believe I'm doing it correctly. I've included an overly simplified version of what I'm trying to do that replicates the problems I'm having.
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = { '1' : hello(),
'2' : goodbye()}
chosen = '1'
options[chosen]()
This is what I get when the above is executed.
Hello
Goodbye
Traceback (most recent call last):
File "main.py", line 12, in <module>
options[chosen]()
TypeError: 'NoneType' object is not callable
And I should just see this.
Hello
Upvotes: 2
Views: 100
Reputation: 851
Just assign the function name as the values in the dictionary
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = {'1': hello,
'2': goodbye}
chosen = '1'
options[chosen]()
Upvotes: 1
Reputation: 12634
Simply remove the parentheses from the functions in the dictionary. Leaving them there causes the functions to be called when the dictionary is declared.
Furthermore you get an error because the values you put into the dictionary are the return values of the functions, i.e., None
, and calling None()
gets you nowhere ;-)
Upvotes: 2