I'm making a program which has a main menu that asks the user to input an option and store it in integer option1, which is looked up in dictionary options. The corresponding function is then run. The following code works if the functions have no parameters:
options = {0 : FunctionZero, # Assign functions to the dictionary
1 : FunctionOne,
2 : FunctionTwo,
3 : FunctionThree}
options[option1]() # Call the function
If the functions have parameters the above code doesn't work as the () part assumes the functions have no parameters, but I tried the following, which stores the functions' names and parameters in tuples within the dictionary:
options = {0 : (FunctionZero,""), # FunctionsZero, FunctionOne
1 : (FunctionOne,""), # and FunctionTwo have no parameters
2 : (FunctionTwo,""),
3 : (FunctionThree,True)} # FunctionThree has one parameter
if options[option1][1] == "": # Call the function
options[option1][0]()
else:
options[option1][0](options[option1][1])
This code seems to work fine, but I was wondering if there's a better way to do this, especially if the functions require several parameters? In other languages like C# I'd probably use a switch or case statement (which is not in Python) and I'm avoiding using if...elif statements for this.