python 中的 eval 函数有问题

Trouble with the eval function in python

我正在尝试计算用户输入的方程式。我将所有数字以字符串形式放入列表中,然后使用 join 函数将其放入一个大字符串中并将其输入 eval 函数。问题是我不断收到错误消息:

使用输入:

Please enter the function: 8x-3
Please enter the smaller x: -6Please enter the larger x: 4
8*x-3

错误信息:

Traceback (most recent call last):
  File "main.py", line 27, in <module>    slope(input("Please enter the function: "), input("Please enter the smaller x: "), input("Please enter the larger x: "))  File "main.py", line 21, in slope
    y1 = eval("".join(f_list))
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

我确保我指定了 x 并且所有内容都是字符串。

这是程序,其中 "function" 是用户输入的方程式:

f_list = []
    for ind, character in enumerate(function):
        f_list.append(character)
        if ind > 0 and character == "x" and is_number(function[ind-1]):
          f_list.insert(ind, "*")

    if not idx:
      print("".join(f_list))
      y1 = eval("".join(f_list))
    else:
      y2 = eval("".join(f_list))

还有:

"".join(f_list)

returns:

8*x-3

当您的 eval() 函数是 运行 时,它试图使用变量 x,您让用户将其作为字符串提供,因此当 eval() 尝试求解您的方程时,它使用的是x 的字符串:即“-6”而不是 -6。

要解决此问题,您必须在调用 eval() 函数之前将 x 转换为整数:x = int(x)。