简体   繁体   中英

python def function and input

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

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 

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM