python中的eval函数遇到问题

问题描述 投票:0回答:1

我正在尝试评估用户输入的方程式。我将所有数字以字符串形式放入列表中,然后使用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并且所有内容都是字符串。

这里是程序,其中“功能”是用户输入的方程式:

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)

返回:

8*x-3
python eval
1个回答
1
投票

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

要解决此问题,必须将x强制转换为整数:x = int(x),然后调用eval()函数。

© www.soinside.com 2019 - 2024. All rights reserved.