我正在为类编写一个计算器程序,当我引用减号、乘号和除号时,我得到了一个字符串索引超出范围的错误,但当我在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
如果输入为:
当到达字符串末尾的
)
时,problem[placeCount + 1]
在字符串之外当运算符为
+
时不会出现错误,因为逻辑运算符执行快捷操作。因为problem[placeCount - (numLength + 2)] == "+"
是真的,所以它从不尝试计算problem[placeCount + 1] == "+"
但是当
problem[placeCount - (numLength + 2)] == "+"
为false时,它会尝试测试problem[placeCount + 1]
。这将访问字符串外部并获取错误将测试更改为:
对于所有其他操作符也是如此
相关问题 更多 >
编程相关推荐