Python 初学者编程:第 3 章错误
Python Programming for the Absolute Beginner: chapter 3 ERROR
所以在这本书第 3 小节 "Creating Intentional Infinite Loops" 作者给出了这个例子:
# 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()
或 return
。问题来了,作者的意思是什么,为什么他会犯这个 - 基本? - 错误?或者也许这不是一个错误,我错过了一些东西。
你能用非常相似和简单的例子帮助我理解 break/continue 函数的概念吗? :)
因为你漏缩了,所以这样做:
# 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
和continue
,还是会有问题,会死循环
缩进在 python 中很重要。所以一定是,
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.")
所以在这本书第 3 小节 "Creating Intentional Infinite Loops" 作者给出了这个例子:
# 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()
或 return
。问题来了,作者的意思是什么,为什么他会犯这个 - 基本? - 错误?或者也许这不是一个错误,我错过了一些东西。
你能用非常相似和简单的例子帮助我理解 break/continue 函数的概念吗? :)
因为你漏缩了,所以这样做:
# 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
和continue
,还是会有问题,会死循环
缩进在 python 中很重要。所以一定是,
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.")