gpt4 book ai didi

python - 为什么我的 protected 循环出错?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:39 25 4
gpt4 key购买 nike

我有这个脚本

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com