Calling a Python function for the text present in a variable

3

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

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

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

or - (Keep in mind that 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 does not work, but is there anything like this?

    
asked by anonymous 12.11.2017 / 06:44

3 answers

2

Boy, I made a prototype of the idea you presented.

In Python there is no Switch Case driver, but you could save your code a lot by incrementing a dictionary (Python data structure) to do something similar, of course you can change and improve the code, but I think I gave a kick-start to adapt as needed.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

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

a = int(input('Digite o valor para A: '))
b = int(input('Digite o valor para B: '))

def switchCase(var, a, b):
    return {
        'adicao' : (a + b),
        'subtracao' : (a - b),
        'multiplicacao' : (a * b),
        'divisao' : (a / b),
    } [var]

print('O resultado é: ', switchCase(func, a, b))

I hope I have helped.

    
19.10.2018 / 15:57
1

Well it seems strange but I ended up solving 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 ...

    
12.11.2017 / 07:03
0

You can do 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)
    
12.11.2017 / 11:33