0

Function as objects in python. Help

Recently i learnt that i can assign a variable the name of the funcion like this: def hello(x):..... greeting = hello print(greeting(a)) and it works... but when i try to give the function the user input it doesn't work. def subtract(x, y):..... def add(x,y):.... operation = input("Which operation do you want to do?") print(operation(3, 4)) How should i fix that? I'd like to rebuild a better version of simple calculator where you can choose the operation and this string becomes the name of the function that you want to call.

18th Apr 2019, 12:06 PM
nicolas
nicolas - avatar
2 Answers
+ 4
You have to distinguish between function object and function call. If you write x=f you store the function. If instead you write x=f() you CALL the function and store what it returns (or None). For example you can store function objects in a dict and call it from there: d = {'function 1': f1, 'function 2': f2} And then call it by accessing the dict. d['function 1']() for example calls f1. So since you get user input as string, you can directly call it using the input. inp=input() # say user writes 'function 1' d[inp]()
18th Apr 2019, 12:17 PM
HonFu
HonFu - avatar