Home > Software engineering >  Python - Define a function based on user's input
Python - Define a function based on user's input

Time:03-14

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 ?

CodePudding user response:

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)
  • Related