[英]How can i use "break" properly into a while loop?
我正在嘗試運行此程序,但我收到錯誤消息:循環中的“中斷”不正確。 我已經搜索了一些答案和錯誤的原因,break 不能在循環語句之外使用。
但是正如您在下面看到的,我正在嘗試在 while 循環中使用“break”。 我是編程新手,所以請不要介意代碼的簡單性。
import random
x = input("Rolar dado? Insira : S/N")
while x == "s":
print("Nº dado:", random.randrange(1,7))
x = input("Rolar dado? Insira : S/N")
else:
break
我希望在用戶輸入“N”后關閉正在運行的程序。
在這種情況下,您不必添加 break,鍵入 N 將覆蓋 while 的條件。 只需刪除 break 語句。
簡而言之,如果您正常退出塊,則執行else
語句,通過達到循環條件,在您的情況下x == "s"
為False
。 如果您break
或return
塊,或引發異常,則不會執行它。
因此,將break
語句放在循環的else
塊中是沒有意義的,因為break
語句旨在終止循環。
"break" 應該只在 while 循環中使用。 您是否試圖停止程序的執行? 如果是這樣,請使用exit()
例如:
import random
x = input("Rolar dado? Insira : S/N")
while x == "s":
print("Nº dado:", random.randrange(1,7))
x = input("Rolar dado? Insira : S/N")
else:
print("Input was not equal to s")
exit()
當您退出縮進段時,while 循環結束,因此由於縮進發生了變化,else 語句不在 while 語句中,這就是它導致問題的原因。
為了獲得您需要的行為,您需要類似的東西
while x == "s":
print("Nº dado:", random.randrange(1,7))
x = input("Rolar dado? Insira : S/N")
if x == "n":
break
只要條件為真,雖然本質上將保持循環。 因此,在您的示例中,您的循環將繼續直到 x == "s",然后它會自動中斷。
#Execute code as long as x is "s"
while x == "s":
print("Nº dado:", random.randrange(1,7))
#Get new input for x
x = input("Rolar dado? Insira : S/N")
#At this point, we've reached end of while loop, it'll check the condition again
#If x is still "s", it'll start over at the print line
#If x is no longer "s" (our condition fails), it stops looping
僅當您需要額外的退出條件時才需要中斷,例如,如果您只想等待最多 3 個輸入,然后中斷,
i = 0
while x == "s":
i = i + 1
print("Nº dado:", random.randrange(1,7))
x = input("Rolar dado? Insira : S/N")
if i == 3:
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.