首页 > 解决方案 > 绝对初学者的 Python 编程:第 3 章错误

问题描述

因此,在本书第 3 章“创建有意无限循环”小节中,作者给出了这个例子:

# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
    count += 1
# end loop if count greater than 10
if count > 10:
    break
# skip 5
if count == 5:
    continue
print(count)
input("\n\nPress the enter key to exit.")

但它不起作用。它只会吐出 break-outside-loop 和 continue-not-properly-in-loop 错误。从我读过的内容来看,break/continue 不能用于跳出 if - 它只能跳出循环,我应该使用sys.exit()or return。问题出现了,作者的意思是什么,为什么他犯了这个 - 基本的? - 错误?或者也许这不是一个错误,我错过了一些东西。

您能否通过非常相似且简单的示例帮助我掌握中断/继续功能的概念?:)

标签: pythonpython-3.xinfinite-loop

解决方案


因为你错过了缩进它,所以这样做:

# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
    count += 1
    # end loop if count greater than 10
    if count > 10:
        break
    # skip 5
    if count == 5:
        continue
print(count)
input("\n\nPress the enter key to exit.")

所以这些行:

# end loop if count greater than 10
if count > 10:
    break
# skip 5
if count == 5:
    continue

得到了一个额外的标签,所以它变成:

    # end loop if count greater than 10
    if count > 10:
        break
    # skip 5
    if count == 5:
        continue

注意:即使去掉breakand continue,还是会有问题,会死循环。


推荐阅读