SnoobySchool
SnoobySchool

Reputation: 33

Python Dictionaries: Running Custom Functions

Please assist me with the following. I've run through a few similar questions of on Stack, but the examples provided do not address the problem that I'm experiencing.

In the dictionary below, I would like to run a custom function when the user types "Option 1".

With the current setup, the custom function - writeFunction() - is executed regardless of which option the user chooses.

The output when choosing 'Option 1':

The output when choosing 'Option 2':

If I change Option 1 to a string value it executes perfectly. What the heck am I doing wrong?

# Custom Function
def writeFunction():
    print("This function works")

# Case statement
def case(arg):
    switch = {
        'Option 1':writeFunction(),
        'Option 2':'Answer 2',
        'Option 3':'Answer 3'
    }
    sysResponse = switch.get(arg,"Value not in list")
    print(sysResponse)

# User selection
userSelection = input("Please select option 1 to 3: ")

# Run case statement based on user selection
case(userSelection)

I want to avoid using endless elif statements.

Upvotes: 1

Views: 276

Answers (1)

AKX
AKX

Reputation: 169032

You could have a reference to the function (notice the lack of () after writeFunction) in the dict, then check whether the object you retrieve to sysResponse is callable; if it is, call it to replace the actual value.

This has the added bonus that if writeFunction has side-effects or is slow to execute, it'll only be executed if it's chosen.

switch = {
    'Option 1': writeFunction,
    'Option 2': 'Answer 2',
    'Option 3': 'Answer 3'
}
sysResponse = switch.get(arg, "Value not in list")
if callable(sysResponse):
    sysResponse = sysResponse()

Upvotes: 2

Related Questions