Calling a Python function by the text present in a variable

Asked

Viewed 1,301 times

3

I am new in Python and I would like to know if it is possible to call a function by the text present in a variable, example:

I ask the user to enter the name of a function, and save what was typed in 'func' , after this how to call the function by what was typed by the user ?

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

or - (Bearing in mind that the functions sum and mult 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 there’s something like this ?

2 answers

1

Well it seems strange but I managed to solve the problem, for those who have the same problem is 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 ! See you later...

0

You can do it like this:

def somar(x, y):
    soma = x + y
    print(soma)

func = input('Digite a função: ')
if func == 'somar':
    x = input('Insira o primeiro número: ')
    y = input('Insira o segundo número: ')
    somar(x, y)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.