本科工程師 Python 入門/While 迴圈
外觀
While 迴圈將在邏輯測試為真時重複一段程式碼。
不用使用已定義值列表或重複一定次數來重複某項操作,while 迴圈會很樂意在邏輯測試滿足之前不斷重複其程式碼部分。可以在 IDLE 中使用“重啟 Shell”來停止無限執行的程式,或同時按住 Control(或 Ctrl)按鈕和 C(字母)。例如
done = False # Creates a variable and gives it the logical vlue 'False'
count = 0 # Creates a variable and gives it integer value 0
while done == False: # Repeats following code until logical test no longer satisfied
count = count + 1 # Adds 1 to value of count variable
print("The value of count is... " + str(count)) # Prints value of count
同一程式碼也可以使用 !=(表示不等於)編寫,例如
done = False
count = 0
while done != True:
count = count + 1
print("The value of count is... " + str(count))