Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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)

Also not sure why you got downvoted. Maybe someone felt this was easily searchable?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading