2016年7月18日 星期一

Python 的迴圈結構

基本迴圈結構:
  • Python 基本迴圈 while 結構:
    while (判斷式):
        執行程式內容
           :
           :
    
  • Python 基本迴圈 for 結構:
    for 變數名稱 in 有多個內容的變數:
        執行程式內容
           :
           :
    
  • Python 迴圈常用的關鍵字:
    關鍵字名稱說明
    break中斷迴圈執行
    continue跳過迴圈執行
    else檢查迴圈運作

快速測試:
  1. 使用互動式指令:
    #python3
    Python 3.4.3 (default, Jan 26 2016, 02:25:35)
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    
  2. While 迴圈基本練習:
    >>> count = 1
    >>> while count <= 5:
    ...    print("Right")
    ...    count += 1
    ... else:
    ...    print("Left")
    ...
    (執行結果)
    Right
    Right
    Right
    Right
    Right
    Left
    
    
  3. 離開互動式指令:
    >>> quit()
    
  4. 編寫 python 程式檔案(while 迴圈):
    $ vim while1.py
    count = 1
    while count <= 5:
      print(count,"\t","Right")
      if (count == 3):
        print("break")
        break
      count += 1
    else:
      print("Left")
    
  5. 執行 python 程式檔案:
    $ python3 while1.py
    1        Right
    2        Right
    3        Right
    break
    
    
  6. 編寫 python 程式檔案(For 迴圈):
    $ vim for1.py
    cats = ["Peter","John","Tom","Judy"]
    for cat in cats:
      if cat == "Tom":
        print(cat,"\t","is Running Away ...")
        continue
      print (cat, "\t","is sitting here..")
    else:
      print ("Cats are All")
    
    
  7. 執行 python 程式檔案:
    $ python3 for1.py
    Peter    is sitting here..
    John     is sitting here..
    Tom      is Running Away ...
    Judy     is sitting here..
    Cats are All
    
    
  8. 編寫更複雜的 For 迴圈程式:
    $ vim for2.py
    cats = {'Persian':'Peter',
            'Aegean':'Judy'}
    for cat in cats.values():
      print ("Cats are :", cat)
    
    for kinds in cats.keys():
      print ("Cats' catogary has:", kinds)
    
    for catogary, cat in cats.items():
      print (catogary," has the cats:",cat)
    
    
  9. 執行 python 程式檔案:
    $ python3 for2.py
    Cats are : Judy
    Cats are : Peter
    Cats' catogary has: Aegean
    Cats' catogary has: Persian
    Aegean  has the cats: Judy
    Persian  has the cats: Peter