Reputation: 77
I am new to Python. I recently learnt that there wasn't a switch case system for python. Instead, the programmer has to make one using the dictionary data type.
I wanted to make a menu system using switch case and the code goes like this :
switch={'1':func1(),'2':func2()} #func1() and func2() are two separate functions (menu options)
choice= input('choice : ')
switch[choice]
Well, in my switch system no matter what I input as 'choice' , func1() runs only.
Any help will be greatly appreciated :)
Upvotes: 0
Views: 82
Reputation: 2424
According to your code, it looks like both func1 and func2 will run every time the code runs. The problem is that when you are declaring your dictionary, you are executing/calling the functions (since you have the ()
after the function name, which is how functions are "called"), instead of just storing a link/reference to them.
In order to pass/store a reference to a function without calling it, just type its name, without ()
at the end. Then, to call a function that was referenced in a variable/somewhere, add the parenthesizes.
This should work:
switch = {'1': func1, '2': func2} # func1() and func2() are two separate functions (menu options)
choice = input('choice : ')
switch[choice]()
Notice how I removed the ()
from the functions on the first line. Also notice on the last line that I am calling the function that is stored in switch
with the key choice
, by adding ()
at the end.
Upvotes: 2
Reputation: 898
Instead of putting func1()
in the dictionary, try putting func1
(no parentheses).
>>> switch = {'1' : func1, # No parentheses here
... '2' : func2 } # ...or here.
>>> choice = input('choice : ')
>>> switch[choice]() # But do put parentheses here.
By putting func1()
in the dictionary, you are actually calling that function and storing its result in the dictionary. If instead you want to call the function through the dictionary, you need to store the function handle (its variable name) and call it after indexing into switch
.
Upvotes: 3