【发布时间】:2018-07-25 20:37:48
【问题描述】:
所以我正在制作一个计算器,它接收一个字符串并检查它是否包含某些单词,例如加法或减法,然后查找整数。但是,在我当前的代码中,我运行它并收到以下错误消息:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 7, in calculator
IndexError: string index out of range
代码在下面输入。
def calculator(string):
if "add" in string or "Add" in string:
total = 0
for i in range(len(string)): #loop for length of string
try:
if type(int(string[i])) == int: #checks to see if there is a number in the string
try:
if type(int(string[i+1])): #checks to see if the number is 2 digits
number_1 = int(string[i])*10
except ValueError:
number_1 = int(string[i])
total = total + number_1 #adds all the numbers to a total variable
except ValueError:
pass
print (total)
如果有人可以帮助我,那就太好了!非常感谢!
【问题讨论】:
-
你的缩进被破坏了。
-
我应该如何解决这个问题?我只是尝试将它们全部重新输入。
-
在任何编辑器中编写代码,然后选择它并按
CTRL+K -
那也没用 :(