【发布时间】:2019-08-31 02:34:09
【问题描述】:
我正在为类制作一个计算器程序,当我提到减号、乘号和除号时出现字符串索引超出范围错误,但在我的系列中首先提到加法时没有得到加号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
【问题讨论】:
-
嗨,你能发布堆栈跟踪吗?
-
Traceback(最近一次调用最后一次):文件“/Users/nick/Desktop/Programs/calculator.py”,第 61 行,在
中如果有问题[placeCount - (numLength + 2)] == "+" 或问题[placeCount + 1] == "+": IndexError: string index out of range -
变量
problem的值是多少 -
您输入的测试字符串有多长?如果第一次迭代中 placeCount 为 0,则从中减去
3并索引问题,字符problem[-3]是什么? -
problem适合哪里?