Disclaimer: see comments, and no, you should not put this in a web page/service which people seem to assume you are writing. However for creating your toy calculator which you run locally at home, this built-in function is enough.
For safety, refer ast
, ast.literal_eval
for really simple cases. simpleeval
has some nice wrapping for ast
, which you may prefer to use as it is and/or learn from it (https://github.com/danthedeckie/simpleeval/blob/master/simpleeval.py) /disclaimer
Assuming you mean the user can enter a function:
f = input("Function of x: ")
x = float(input("x: "))
print(eval(f))
Then enter x+2
for the first input, 2
for the second, and see the result becoming 4
:
Function of x: x+2
x: 2
4
For making it more versatile, you may want to import everything from math
:
from math import *
f = input("Function of x: ")
x = float(input("x: "))
print(eval(f))
then you can input cos(x)
for example:
Function of x: cos(x)
x: 3.1415
-0.9999999957076562