你究竟知道它會不會終止?有沒有一個讓它繼續前進的功能?如果我想在一定次數後停止循環,我會怎麼做?如何判斷while循環是否會終止?
回答
甲while
循環終止
如果它使用的條件是在它被評估的時間假。
實施例:
x = 10 while x > 5: x -= 7 print x x += 6 print x
依次將打印的數字3,9,2,8,1,7,0,6,-1,5,然後才終止。
x
在執行期間變成<= 5
,但只有在重新啓動循環時的狀態是相關的。如果它與
break
同時左:x = 10 while x > 5: print x x -= 1 break
只能打印10,因爲它只是在 「強制」 之後。
它運行的一定次數會做
x = 0
while x < n:
do_stuff()
x += 1
或更好地爲一個循環:
for x in range(n):
do_stuff()
你忘記了第三個選項:執行一個return語句。 –
@NoctisSkytower右,或者一個異常,或者一個'sys.exit()'或者'sys._exit()'。 – glglgl
從技術上講,'sys.exit()'引發了一個'SystemExit'異常。 –
一般情況下,這是不可能提前知道是否計劃將永遠循環或最終停止。這被稱爲Halting problem。當然,在實踐中,你可以通過查看條件來做出合理的猜測。
只要條件成立,while循環將繼續進行。你不需要一個函數來繼續。
while True:
print "hello, world!"
#no functions required here!
如果你想要的東西循環一定的次數,這是最好使用一個for循環:
for i in range(10):
print "hello, world!"
#prints ten times
雖然你仍然可以使用while循環,如果你真正想要的。
count = 0
while count < 10:
print "hello, world!"
count += 1
我甚至可能會爲'範圍(10):'明確表示該參數不會被使用,但這只是風格(+1)的問題。很好的答案。 – mgilson
- 1. while循環不會終止?
- 2. while循環是否會停止執行?
- 3. while循環不會終止正確
- 4. while循環終止問題?
- 5. while循環終止重寫?
- 6. while循環不終止?
- 7. 非終止while循環
- 8. while循環不會停止循環Java
- 9. JOptionPane在while循環內顯示while循環後終止
- 10. 如何判斷JavaScript函數從while循環獲取哪個id?
- 11. 如何判斷方法或循環是否完成?
- 12. 如何停止While循環?
- 13. 終止while循環後Cant cin
- 14. 定時while循環不終止
- 15. 爲什麼我的while循環終止?
- 16. 爲什麼While循環終止?
- 17. 嘗試使用'。'終止while循環
- 18. 簡單的while循環不會中斷
- 19. 如何終止forEachObject循環?
- 20. while循環光標和動態SQL不會終止
- 21. C++:while循環不會終止爲NULL,我錯過了什麼?
- 22. while循環將不會以邏輯條件終止
- 23. 無限循環或提前終止做while循環
- 24. 在while循環中使用scanf(),但循環不終止
- 25. 我們如何確保while循環不會是無限循環?
- 26. 如何用if語句在C++中的do-while循環中終止for循環?
- 27. 如何在while循環中寫條件來終止它
- 28. 如何在while循環中終止do方法?
- 29. 如何在字符匹配時終止while循環'。'在c
- 30. bash while循環不會自行停止
'while cnt <10:'竅門 – TJD
@TJD - 你是什麼意思?如果你不在循環內用'cnt'做任何事情,Taht將循環無限次(或者沒有次數)。如果你真的想迭代一定次數,用''xrange'或'range'來'for' ... – mgilson