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

标签 python while-loop

我有这个脚本

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/

相关文章:

python - RNN 的 tf.clip_by_value 和 tf.clip_by_global_norm 之间的区别以及如何确定要剪辑的最大值?

php - 为什么总是使用 "while"循环来迭代 mysql_fecth_array() 函数结果?

Python - 多线程/多处理

c - 在 C 中用 scanf 循环

C编程: how to implement an insertion sort?

c++ - 为什么一行输出(在 while 循环中)使不变量为假?

android - 您如何检测声音文件何时完成?

python - 定时器可重新启动

python - 如何将带有表情符号名称的字符串转换为不和谐的表情符号?

python - unittest 中的 assertRaises 没有正确捕获异常