Ole
Ole

Reputation: 23

Executing a function in a dictionary | Python 3

So I am making a program in python 3.6 that selects and executes a specific function based on the user_input.

The code can properly decide what function to execute, just not actually execute it. The functions also work

def addition():
    1+1

user_input = input("What operator do you wish to use?")

myOperators = {"Addition":addition}

if user_input in myOperators:
    myOperators.get(user_input)

Using this code the function addition() never executes. However, I can check that it selects the correct value, because if I do this:

if user_input in myOperators:
    print(myOperators.get(user_input))

it prints <function addition at 0x7f0973026620>

Upvotes: 2

Views: 59

Answers (1)

James
James

Reputation: 36658

Python treats functions as object which can be passed around and stored in lists and dictionaries. To actually call the function you need to use parenthesis after the object.

In your case myOperators.get(user_input) returns the function object, so it would become

myOperators.get(user_input)()

Upvotes: 4

Related Questions