Reginald Reginald - 2 months ago 5
Python Question

Trying to use a switch case similarity in Python, but somehow first choice always runs first

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: ")


It's great that it prompts user for input, but regardless of number I write, it always runs choiceone.

I'm somewhat new to Python, probably it's a big mess for those that do know what I just did, but I'm just trying to see how I can go in invoking a function based on user selection.

Thanks in advanced!


Here's a working example of your code:

def choiceone():

def choicetwo():

def default():

def switching(x):
    return {
        1: choiceone,
        2: choicetwo,
    }.get(x, default)

if __name__ == "__main__":
    user_input = int(input("Choice: "))

    your_choice = switching(user_input)

As you can see, in the above code I'm returning just the functions and storing them into your_choice variable, then i can just run them as any other function your_choice()