【问题标题】:Python - break statement not working in else statement within while loopPython - 中断语句在while循环中的else语句中不起作用
【发布时间】:2021-04-15 07:47:34
【问题描述】:

当我使用 break 语句时,我的代码中的 while 循环拒绝终止,我真的很困惑为什么会这样。

point = 0
while point < len(list_of_line_lists) - 1:
    sentence = list_of_line_lists[point]["text"]
    datapoint = point
    while True:
        try:
            if list_of_line_lists[datapoint]["author"] == list_of_line_lists[datapoint + 1]["author"]:
                sentence += list_of_line_lists[datapoint + 1]["text"]
                datapoint += 1
                print(datapoint)
            else:
                print("this isn't breaking")
                break
        except IndexError:
            break

在我上面的代码中,else 语句中的 break 语句拒绝触发。其中的代码被执行,因为输出中有一阵“这没有破坏”,但循环本身并没有终止。这就是我的输出的样子(直到我自己手动停止它):

this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking
this isn't breaking

对为什么会发生这种情况有任何想法吗?

【问题讨论】:

  • 你有两个while 循环,break 只会退出内部循环。您是否在外部while 循环的末尾(或开头)放置了任何代码以查看是否确实存在问题?您的外部循环正在查看 point 变量的值,并且看起来您从未更改过它(或循环内的 list_of_line_lists 变量。
  • 它打破了内循环,但没有打破外循环。
  • 好的,是的,这是一个愚蠢的错误,我忘了增加点变量。我真的是睡眠不足,非常感谢您的建议! @larsks

标签: python python-3.x loops break


【解决方案1】:

内循环正在中断,但外循环没有。原因是您在外部 while 循环中使用了 point 变量,但 (point) 变量值从未更改(递增/递减)。

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2015-11-08
    相关资源
    最近更新 更多