How to dynamically define the function to be called in Python

Asked

Viewed 58 times

1

Hello, I would like the program user to write a function for later use, however I’m having difficulty to implement this:

See the example below:

def funcao_integracao(x):
    y=x**2
    return y

def trapezio():
    intervalo = []
    val = 0

    intervalo.append(float(input("Digite o intervalo inferior de integração: ")))
    print(' ')
    intervalo.append(float(input("Digite o intervalo superior de integração: ")))
    print("Digite o número de iterações: ")

    it = int(input("=>"))
    h = (intervalo[1] - intervalo[0])/it
    for i in range(it):
        val += h/2*(funcao_integracao(intervalo[0]+(h*i))+funcao_integracao(intervalo[0]+(h*(i+1))))
    print("A integração da função no intervalo {} até {} com {} iterações é: " .format(intervalo[0], intervalo[1], it), val)

In funcao_integracao(x), instead of the program using a predefined function (x**2), would like the user to inform the function he wants.

EDITED BY de_python

An alternative would be to use the function

def funcao(func, x):
    if 'x' in func:
        func = func.replace('x','{x}')
    func = func.format(x=x)
    return eval(func)

You can choose which account will be in the first position, for example:

funcao("10**x", 2)

Where the return is

100
  • I don’t understand. You want the user to choose between functions you set or if you want the user to write their own function?

  • I would like the user to write the function itself

  • 1

    The question is clear to me. Only the title was not very good. I suggested a few issues to get everything more aligned.

  • You can use f-string to create dynamic text, where the x of the function is the text of the account it wants. For example def funcao(func, x): if 'x' in func: func = func.replace('x','{x}') func = func.format(x=x) Return Eval(func) funcao("10**x", 2) ==> 100

  • I did not agree with the closing of the question. For me it is clear and I have a good answer to give, even more with the recent editions.

No answers

Browser other questions tagged

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