简体   繁体   中英

How do I accept a function as an input?

I'm trying to write a program that accepts and evaluates a simple function as such:

A=[]
v = input("Enter Function of x: "
o = input("Enter length of range: ")

for x in range (1,o+1):
    f = (v)
    A.append(f)

but this just returns the function text (input string) 'o' times in a list. What am I doing wrong?

EDIT: Thanks to @tdelaney for the answer: use f=eval(v)

v is merely a character string. Throwing parentheses around it makes it a tuple of one element -- the same string. You haven't done anything to turn it into a function -- which is not trivial in any programming language, as you're trying to inject new code into a program that has already been parsed.

Python supplies the eval function for doing this. Beware, however, as eval is quite powerful and dangerous.

my_func = "x*x + 2*x - 3"
limit = 5
y_vals = []

for x in range (1,limit+1):
    y_vals.append(eval(my_func))

print(y_vals)

Output:

[0, 5, 12, 21, 32]

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