1

I'm writing a program that involves calculating the maximum of a user defined function, however if the user enters a function in terms of a variable such as x, i.e.

input = x**2 + 2*x + 1

I (fairly expectedly) get an error as x is not defined.

Does anyone know of an effective way to allow a user to input a function in terms of a single variable such as x?

Bill the Lizard
407k213 gold badges579 silver badges892 bronze badges
asked Dec 12, 2011 at 21:46
2

1 Answer 1

2

If you are not worried about security much, simplest solution is to eval the expression e.g.

def calculate(value, function):
 x = value
 return eval(function)
print calculate(2, "x**2 + 2*x + 1")
print calculate(2, "x**3 - x**2 + 1")

output:

9
5

You can make it more secure by passing an empty builtin dict but still I think some clever code will be able to access internals of your code.

answered Dec 12, 2011 at 21:49
Sign up to request clarification or add additional context in comments.

4 Comments

And then the user can input a value if you used the int(raw_input(...)) strategy @bpgergo suggested.
@Jon yes there can be various ways to get x value and function string from user e.g. from gui or command-line or from an API
The only thing i can add that maybe would be better to use docs.python.org/library/…
@ArtsiomRudzenka thanks I may edit that, but I don't think it evaluates such expressions

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.