python - 绝对初学者的 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
。问题出现了,作者的意思是什么,为什么他犯了这个 - 基本的? - 错误?或者也许这不是一个错误,我错过了一些东西。
您能否通过非常相似且简单的示例帮助我掌握中断/继续功能的概念?:)
解决方案
因为你错过了缩进它,所以这样做:
# 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
注意:即使去掉break
and continue
,还是会有问题,会死循环。
推荐阅读
- python - 优化 Python 代码以量化浮点数序列
- neo4j - 如何阻止 Neo4J Cypher 处理空集合?
- html - 需要 HTML5 表单输入 - 使用 Canvas
- r - R:一次grep多个字符串
- encryption - 使用 sha1 解密代码,之前附加了盐
- javascript - 有没有办法使用 addEventListener 将 contenteditable 内容自动保存到 sqlite 数据库?
- java - SQL 查询结果到 Java 数组
- xml - 如何在 XML Schema 中元素范围内的任何位置定义 maxOccurs?
- json - 依赖角度的选择框不起作用
- swift - iOS CloudKit 在查询繁重的 CKAsset 时很慢(即使有 QoS)