Call a Python function from the text present in a variable


I'm new to Python and I would like to know if it's possible for me to call a function by the text present in a variable, example:

I ask the user to type the name of a function, and keep what was typed in 'func' , after that how to call the function by what was typed by the user?

func = input('Diga o nome da função a ser executada!')

or – (Bearing in mind that the add and mult functions are already done)

func = 'somar'
result1 = func(3, 2)
func = 'mult'
result2 = func(3, 2)
print('O resultado é', result1, result2)
#---gostaria que resultasse
O resultado é 5 6

I know this doesn't work, but is there something like this?


Well it looks strange but I ended up managing to solve the problem, for those who have the same problem it's very simple:

executar = locals()
func = 'somar'
result1 = executar[func](3, 2)
func = 'mult'
result2 = executar[func](3, 2)
print('O resultado é', result1, result2)

That's all :D! Until later…

Scroll to Top