我有这个脚本
for line in file:
while line[i] == " ":
if i == len(line):
break
i += 1
if i == len(line):
pass
while not line[i] == " ":
if i == len(line):
break
obj += line[i]
i += 1
print obj
到目前为止,file
等于 ["clear", "exit"]
且 i
等于 0
.
当我运行这个脚本时,它会出现这样的错误
Traceback (most recent call last):
File "/home/ubuntu/workspace/lib/source.py", line 8, in <module>
while not line[i] == " ":
IndexError: string index out of range
我很确定我的循环受到了正确的保护,并且它应该在这种情况发生之前中断。如果是这样,那么为什么会发生呢?
最佳答案
my loop is protected
不,不是。 while
上的条件在到达循环体之前必须先进行评估,其中保护 if
条件是。
可以肯定的是i
不超过列表长度,将条件移至 if
并将其作为 while
的第一个条件:
while i < len(line) and not line[i] == " ":
obj += line[i]
i += 1
否则您可以移动 if
i
更新后阻止因此,在 while
的下一次迭代之前评估条件:
while not line[i] == " ":
obj += line[i]
i += 1
if i == len(line):
break
关于python - 为什么我的 protected 循环出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758857/