[SOLVED] Python – Define a function based on user's input


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


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


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()

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 ?


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

For instance:

x = 3
string = 'x + 3'
# 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)

Answered By – Josh

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *