-1

I am trying to set up a function using input , Is this possible ?

function = input('Please enter a function example')
def f(x): 
 return function 
print(f(2))

So if the function input is x**2 it should print the num 4 . I know this syntax is not right because functions is an alphanumeric object , but I need your help to understand how to make it right

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • 6
    Unless you abuse `eval` here, you're going to likely need to write an expression parser, which is no simple task. Is this just a toy project? – Carcigenicate Nov 06 '18 at 15:13
  • Take a look in this [question](https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python) – Hemerson Tacon Nov 06 '18 at 15:17

2 Answers2

-3

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
tevemadar
  • 12,389
  • 3
  • 21
  • 49
-3

I assume that you mean letting a user enter code (the function) as the input. If this is the case this might be a duplicate from:

In Python: How do I convert a user input into a piece of code?

sanchedale
  • 166
  • 1
  • 7