Python 使用函数中的两个变量评估用户输入的方程
我随机选择了x=1和y=2,但我需要让函数在整个程序中为不同的x和y值工作。您可能正在寻找类似的东西:Python 使用函数中的两个变量评估用户输入的方程,python,function,Python,Function,我随机选择了x=1和y=2,但我需要让函数在整个程序中为不同的x和y值工作。您可能正在寻找类似的东西: function=print(input('Enter a function in terms of x and y: ')) def f(x,y): evaluated=eval(function) return evaluated print(f(1,2)) 从输入行中删除打印,代码将变为 function = input('Enter a function in t
function=print(input('Enter a function in terms of x and y: '))
def f(x,y):
evaluated=eval(function)
return evaluated
print(f(1,2))
从输入行中删除打印,代码将变为
function = input('Enter a function in terms of x and y: ')
def f(x, y):
evaluated = eval(function)
return evaluated
x = int(input('x: '))
y = int(input('y: '))
print(f(x, y))
以这种方式使用eval对于生产代码是不安全的
它可以通过以下方式变得更安全
发布代码的问题
def f(x,y):
evaluated = eval(function)
return evaluated
function = input('Enter a function in terms of x and y: ')
print(f(1,2))
在这一行中,用户输入的任何内容都通过打印例程打印到屏幕上
打印例程不返回分配给函数的任何内容。这可能就是您要查找的内容
function=print(input('Enter a function in terms of x and y: '))
尽管@DarrylG建议不建议以这种方式使用eval()
在你的代码中
def f(x,y):
evaluated = eval(function)
return evaluated
function = input("Enter a function in terms of x and y:")
x = int(input("Enter a number"))
y = int(input("Enter a number"))
print(f(x,y))
您似乎已将print语句分配给变量,该变量返回none。因此,变量被分配到非类型。变量函数被设置为无(即打印结果)。我不确定“函数被设置为无”是什么意思。您好,我希望用户输入函数并输出函数的答案(对于我选择的任何x和y值)。希望这有道理。明白了,我编辑了答案。这也正是其他SO成员所指的。确保遵循DarryIG的
eval
建议。@MayBrekker——不客气。别忘了
function=print(input('Enter a function in terms of x and y: '))