引用不同的if语句时字符串索引超出范围

2024-09-29 21:54:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为类编写一个计算器程序,当我引用减号、乘号和除号时,我得到了一个字符串索引超出范围的错误,但当我在if/elif语句系列中首先引用加法时,没有得到加法符号的索引

problem = ("123 * 456")
numLength = 0
placeCount = -1
for i in problem:
    placeCount = placeCount + 1
    if i == "0" or i == "1" or i == "2" or i == "3" or i == "4" or i == "5" or i == "6" or i == "7" or i == "8" or i == "9":
        numLength = numLength + 1
        holdingList.append(i)
    if i == " " or i == ")" and numLength > 0:
        theNum = concatenate_list_data(holdingList)
        if problem[placeCount - (numLength + 2)] == "+" or problem[placeCount + 1] == "+":
            theNum = int(theNum)
            adding.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "-" or problem[placeCount + 1] == "-":
            theNum = int(theNum)
            subtracting.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "*" or problem[placeCount + 1] == "*":
            theNum = int(theNum)
            multing.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "/" or problem[placeCount + 1] == "/":
            theNum = int(theNum)
            dividing.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""

错误:

Traceback (most recent call last):
    File "/Users/nick/Desktop/Programs/calculator.py", line 61, in <module>
      if problem[placeCount - (numLength + 2)] == "+" or problem[placeCount + 1] == "+":
    IndexError: string index out of range

Tags: or字符串in程序if错误计算器int
1条回答
网友
1楼 · 发布于 2024-09-29 21:54:57

如果输入为:

problem = '(123 * 456)'

当到达字符串末尾的)时,problem[placeCount + 1]在字符串之外

当运算符为+时不会出现错误,因为逻辑运算符执行快捷操作。因为problem[placeCount - (numLength + 2)] == "+"是真的,所以它从不尝试计算problem[placeCount + 1] == "+"

但是当problem[placeCount - (numLength + 2)] == "+"为false时,它会尝试测试problem[placeCount + 1]。这将访问字符串外部并获取错误

将测试更改为:

if problem[placeCount - (numLength + 2)] == "+" or (placeCount < len(problem) - 1 and problem[placeCount + 1] == "+"):

对于所有其他操作符也是如此

相关问题 更多 >

    热门问题