'Trying to use a switch case similarity in Python, but somehow first choice always runs first [duplicate]
I am aware that Python doesn't have a switch case like C++, but I'm trying to figure out how to go about it and found something, but not sure if it's implemented correctly.
So I have something like:
def choiceone():
choiceone statement here
def choicetwo():
choicetwo statement here
def switching(x):
switcher= {1: choiceone(),
2: choicetwo(),
}
func = switcher.get(x, 0)
return func()
def main():
user_input=input("Choice: ")
switching(user_input)
main()
It's great that it prompts user for input, but regardless of number I write, it always runs choiceone.
I'm trying to see how I can go in invoking a function based on user selection.
Solution 1:[1]
Convert your user_input from string to int and don't call the functions in your switcher dictionary:
def choiceone():
# choiceone statement here
print "function 1"
def choicetwo():
# choicetwo statement here
print "function 2"
def switching(x):
switcher= {1: choiceone, # Don't call the function here
2: choicetwo,
}
func = switcher.get(x, 0)
func() # call the choice of function here
def main():
user_input = int(input("Choice: ")) # Convert to int
switching(user_input)
main()
Solution 2:[2]
By calling the switching function, you are storing the result of the choiceone function as the value of the 1 key because you called the function.
You just need the function name without the parenthesis to hold the function reference.
Same with the return statement, unless you want to call the function there. If you want to return the function itself, you could call switching(user_input)() because switching(user_input) would return a function handle
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhishek Balaji R |
| Solution 2 | OneCricketeer |
