我正在为类编写一个计算器程序,当我引用减号,乘号和除号但未获得加号时,我得到的字符串索引超出范围错误,因为我在本系列中首先提到加法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
答案 0 :(得分:0)
如果输入是:
problem = '(123 * 456)'
当您到达字符串末尾的)
时,problem[placeCount + 1]
就在字符串之外。
当运算符为+
时,您不会出错,因为逻辑运算符会执行快捷方式。由于problem[placeCount - (numLength + 2)] == "+"
是真实的,因此它永远不会尝试评估problem[placeCount + 1] == "+"
。
但是,当problem[placeCount - (numLength + 2)] == "+"
为假时,它将尝试测试problem[placeCount + 1]
。这会访问字符串之外的内容并得到错误。
将测试更改为:
if problem[placeCount - (numLength + 2)] == "+" or (placeCount < len(problem) - 1 and problem[placeCount + 1] == "+"):
,其他所有运算符也是如此。