for loop 與 while loop 的差異
執行方式
for loop 的執行方式 是依據一個數字的範圍(次數)做執行,例如,搭配 list 或 range( ) function 使用。 次數跑完了,for loop 才會停止。
while loop 的執行方式 是依據一個條件是否成立,條件成立內,while loop 會一直執行下去。 當執行條件不成立時,while loop 才會停止。
語法
for loop 的語法 keyword in 結尾後面,必須以冒號(colon),做為結束。
while loop 的語法 起始 keyword while,空一格,接著一個判斷條件,結尾,一樣需要加上冒號(colon)。 要重複執行的事情,一樣需要縮排,變成 while loop 的程式碼區塊。
for item in list_of items:
#Do something to each item
for number in range(a, b):
print(number)
while something_is_true:
#Do something repeatedly
Line 19 在 while loop 的程式碼區塊的最後一行,每次執行到這邊,就遞減1。 目的是為了,最後讓 while loop 停下來,當 number_of_hundles = 0 時 。
**Line 20 觀察,**每次遞減1後的結果。
def turn_right():
turn_left()
turn_left()
turn_left()
def jump():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
number_of_hundles = 6
while number_of_hundles > 0:
jump()
number_of_hundles -= 1
print(number_of_hundles)
Line 16 在 while loop 的判斷條件,為 at_goal( ) 不等於 True。 at_goal( ),代表是終點(有旗子)。
所以,只要那一步(x, y)不是終點的話,while loop 就會持續執行下去。
def turn_right():
turn_left()
turn_left()
turn_left()
def jump():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
while at_goal() != True:
jump()
Line 16 在 while loop 的判斷條件,為 not at_goal( )。 at_goal( ),代表是終點(有旗子)。