6.whileloop

Java雜記發表於2016-09-05
while 迴圈
 
有時候我們不確定需要迴圈幾次。就像一個司機不知道自己需要什麼時候加油一樣。程式可以這樣寫:
 
while petrol_filling:
increase price
show price
add petrol
 
python有while語句。讓我們來建立一個猜數字的遊戲吧:
 
x = 0
while x != 5:
x = int(input(“Guess a number:”))
 
if x != 5:
print(“Incorrect choice”)
 
print(“Correct”)
 
它會一直判斷數字知道猜對,這一行的定義是while x != 5, or in English,當x不等於5時候,執行。
 
示意圖:
 
當條件判斷為真的時候程式碼會不斷重複,會一直重複到x=5.
 
死迴圈
如果條件是不可能滿足的,這就會造成程式一直執行到當機。