[5] while & for 重複迴圈


Posted by bessyhuang on 2023-05-20

💡 Python 沒有 do...while 語法。

While Loops

while [condition1]:
    [statement 1]
else:
    [statement 2]
# 巢狀 while 迴圈
while [condition 1]:
    [statement1]
    while [condition 2]:
        [statement2]
    else:
        [statement3]
else:
    [statement4]

語法

  • 透過條件成立與否,來控制執行次數。
  • statement 中特殊的語法
    • continue - 結束當前迴圈狀態進到下一個迴圈
      • With the continue statement we can stop the current iteration, and continue with the next.
    • break - 跳出/強制離開 當前迴圈
      • With the break statement we can stop the loop even if the while condition is true.
    • pass - 佔位語句,不做任何事,是為了保持程式碼結構的完整性
        💡 只要是在程式碼裡的執行區塊內,pass 都可以使用!
      

程式碼解釋

  • 只要判斷為 True,便能一直執行 statement1 的程式碼(不限次數)。
  • 如果為 False 的話,就跳到 else 的部分執行 statement2 程式碼後才結束。

範例

  • while

      i = 1
      while i < 3:
          print(i)
          i += 1
    
      # 1
      # 2
    
  • while..else

      count = 0
      while count < 5:
         print(count, " is  less than 5")
         count = count + 1
      else:
         print(count, " is not less than 5")
    
      # Output:
      # 0  is  less than 5
      # 1  is  less than 5
      # 2  is  less than 5
      # 3  is  less than 5
      # 4  is  less than 5
      # 5  is not less than 5
    
  • while + continue

      i = 0
      while i < 6:
          i += 1
          if i == 3:
              continue
          print(i)
    
      # 1
      # 2
      # 4
      # 5
      # 6
    
  • while + break

      i = 0
      while i < 6:
          i += 1
          if i == 3:
              break
          print(i)
    
      # 1
      # 2
    
      i = 0
      while i < 6:
          print(i)
          if i == 3:
              break
          i += 1
    
      # 0
      # 1
      # 2
      # 3
    
  • while + pass

      number = eval(input())
      while number > 10:
          pass
          # 還不確定要做甚麼動作時,先用 pass 佔位,保持程式碼結構的完整性
      else:
          print("Less than 10.")
    
      count = 0
      while count < 5:
          count += 1
          if count % 3 == 0:
              pass
          else:
              print(count)
    
      # Output:
      # 1
      # 2
      # 4
      # 5
    
      # 若「pass 該行直接為空」,則出現「 IndentationError: expected an indented block 」。
    
  • 連續且重複的情況下,可使用 while 來減少程式碼撰寫

      # 從 1 到 100 的總和
    
      counter = 0
      total = 0
    
      while counter < 100:
          counter += 1
          total += counter
    
      print('The Summary from 1 to 100 is', total)
    
  • 通常也會使用 while 來處理連續輸入

      while True:
          string = input('Please enter any word:')
          print(string)
    
      # 當輸入 Ctrl + z 或者 Ctrl + c 時,便停止輸入。
    

For Loops

for [var] in [iterable]:
    [statement1]
else:
    [statement2]
# for 巢狀迴圈,唯一要注意的點在於 var1, var2 不能重複

for [var1] in [iterable]:
    for [var2] in [iterable]:
        [statement]

語法

  • 使用可迭代物件 (iterable),來控制執行次數。
    • To loop through a set of code a specified number of times.
    • 可迭代物件 (iterable)
      • 如:list, tuple, dictionary, set, string。
      • 可使用 slicing(切片)索引(index) 來取出可迭代物件內的元素。

程式碼解釋

  • for 迴圈有兩個部分需要設置
    • var - 自行設定的變數,表示可迭代物件中被遍覽的元素。
    • iterable - 可迭代物件,可以被 for loop 遍歷/逐一取出內部資料的東西,用以被遍歷其中的所有元素。
  • Python for 迴圈的概念為「遍歷/逐一取出內部資料」,相當於 C 語言的 foreach。
💡 for 迴圈在 python 的寫法設計 與 C / C++ 不相同。

* Python   把所有東西看作 object 來處理。
    # foreach concept
    for i in ['apple', 'banana', 'peach']:
        print(i)

    # counter concept => range(start=0, stop [, step=1])
    for i in range(0, 7, 2):       # but not including 7
        print(i, end="\t")

* C / C++  設定狀態 (Initialization, Condition, Update) 來處理迴圈。
    * Initialization - 用以初始設定迴圈的 Counter
    * Condition - 用以判斷迴圈結束的條件
    * Update - 用以設定迴圈 Counter 的變化

    #include <stdio.h>
    int main() {
        int i;
        for (i = 0; i <= 6; i = i + 2) {
            printf("%d\t", i);
        }
        return 0;
    }

範例

  • 字串
      sent = "我的肝呢?"
      for w in sent:
          print(w)
    
  • List
      fruits = ['apple', 'banana', 'grape']
      for f in fruits:
          print(f)
    
  • Tuple
      fruits = ('apple', 'banana', 'grape')
      for f in fruits:
          print(f)
    
  • for..else

      for x in range(6):
          print(x)
      else:
          print("Finally finished!")
    
      for x in range(6):
          if x == 3: 
              break
          print(x)
      else:
          print("Finally finished!")
    
      # If the loop breaks, the else block is not executed.
    
  • for + break
      fruits = ["apple", "banana", "cherry"]
      for x in fruits:
          print(x)
          if x == "banana":
              break
    
      fruits = ["apple", "banana", "cherry"]
      for x in fruits:
          if x == "banana":
              break
          print(x)
    
  • for + continue
      fruits = ["apple", "banana", "cherry"]
      for x in fruits:
          if x == "banana":
              continue
          print(x)
    
  • for + pass
      for x in [0, 1, 2]:
          pass
    
  • for 巢狀迴圈
      for i in range(2, 10):
          for j in range(1, 10):
              print('{} * {} = {}'.format(i, j, i*j), end='\t')
          print()
    

while vs. for

i = 0
while i < 5:
    print(i)
    i = i + 1

#相當於
for j in range(5):
    print(j)

#Python #While Loop #For Loop







Related Posts

作業 14 週、筆記

作業 14 週、筆記

css selector 自己看

css selector 自己看

HTB Timelapse Walkthrough

HTB Timelapse Walkthrough


Comments