如何将用户输入视为代码输入?

时间:2017-04-16 21:29:57

标签: python string input

当用户使用输入命令输入多功能时,我试图让函数返回特定格式的多项式。然而,即使使用eval(input()),我理解这是一种糟糕的做法,让它陷入循环。以下是我的代码:

def func(x):
    function = eval(input("enter a string in the format (x - 3) * (x - 5) * (x - 7) + 85")) #should run this as code so horid security, but still busted
    return function

我希望它的运作方式如下:

def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85

如果用户要输入该功能,但如果用户输入该格式的任何多项式,也可以使用。

这似乎很普遍,我认为至少我可以用eval(input())来欺骗它,但是使用eval会使程序陷入循环,提示用户无限期地输入该函数

2 个答案:

答案 0 :(得分:2)

eval仅评估表达式。您可以使用lambda

在表达式中定义函数
f = eval('lambda x: ' + input())

这相当于def f(x): return ...

答案 1 :(得分:1)

如何创建用户输入的功能。

import functools
formula = input('enter formula.')
f = functools.partial(eval, formula)

现在f是你通过这样做调用的多项式函数。

result = f([arg1, arg2, arg3, argN])