0

I have a function taking a function and a float as inputs, for example

def func_2(func, x):
    return func(x)

If a function is defined in advance, such as

def func_1(x):
    return x**3

then the following call works nicely

func_2(func_1,3)

Now, I would like the user to be able to input the function to be passed as an argument to func_2.

A naive attempt such as

print("enter a function")
inpo = input()

user types e.g. x**3

func_2(inpo)

returns an error as a string is not callable.

At the moment I have a workaround allowing user to only input coefficients of polynomials, as in the following toy example

def funcfoo (x,a):
    return x**a
print("enter a coefficient")
inpo = input()
funcfoo(3,int(inpo))

it works as I convert the input string to an integer, which is what the function call expects.

What is the the correct type to convert the input function, to work as first argument of func_2 ?

0

1 Answer 1

3

I think you're looking for the eval() function. This will change a string to a function.

For instance:

x = 3
string = 'x + 3'
eval(string)
# Returns 6

This does require you to modify your initial function a bit. This would work:

def func_2(func, x):
    func_new = func.replace('x', str(x))
    return eval(func_new)


inpo = 'x + 3'

func_2(inpo, 3)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot. I might have searched in the wrong places, but did not come remotely across it.
Glad to help. Added some more code in case you get stuck, since I realized I didn't actually answer your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.