Python代碼結構——順序、分支、迴圈

來源:互聯網
上載者:User

標籤:statement   bsp   進入   bre   相對   TE   ict   ##   程式   

## 順序結構
  - 按照從上到下的順序,一條語句一條語句的執行,是最基本的結構


## 分支結構
  if condition:
    statement
    statement
    ...
  elif condition>:  
    statement
    statement
    ...
  else:
    statement
    statement
    ...
  - if 語句可以嵌套,但不推薦, 盡量保持代碼簡潔
  - Python沒有switch-case語句
  - Python條件陳述式允許下列寫法
    x = 10
    print(1 < x < 20) # -> True
    print(1 < x < 20 < 100) # -> True
  - 以下資料將被判定為False:
    False、None、0、0.0、""、[]、()、{}、set()

 

## 迴圈結構
  - 寫迴圈程式時需要注意迴圈變數的初值,迴圈條件和迴圈變數的增量,三者共稱為迴圈三要素
  - while迴圈
    count = 0 # -> 迴圈變數
    while count < 5: # -> 迴圈條件
    print(count, end=",") # -> 0,1,2,3,4,
    count += 1 # -> 迴圈變數的增量,對迴圈變數進行修改


  - for迭代
    - 在C或者Java等語言中,for迴圈將迴圈三要素結合在一行語句中:大概如下:
      for(int i = 0; i < 10; i++){迴圈體}
    - 但Python中的for迴圈相對而言更加簡潔
      words = ["and", "or", "not"]
      for word in words:
        print(word, end=", ") # -> and, or, not,
    - 列表、元組、字典、集合、字串都是可以迭代的對象


  - 對字典的迭代可以:
    a_dict = {"name": "Stanley", "age": "22"}
    for k, v in a_dict.items():
      print("{0}: {1}".format(k, v))
    # -> name: Stanley
      age: 22
  - 單獨迭代字典的key或者value可以使用字典的keys()或values()函數


  - break關鍵字
    - 在迴圈體中使用break關鍵字,整個迴圈會立刻無條件停止
      count = 0
      while count < 5:
        if count == 2:
          break
        print(count, end=" ")
        count += 1

      # -> 0 1

      # -> 由於當count等於2時,進入if語句執行了break,所以迴圈結束,未完成的迴圈不再執行


  - continue關鍵字
    - 在迴圈體中使用continue關鍵字,此次迴圈無條件體停止,執行之後的迴圈

      for i in range(0, 5):
        if i == 2:
          continue
        print(i, end=" ")
      # -> 0 1 3 4
      # -> 當i等於2時進入if語句,執行continue,本次迴圈跳過,進入下一迴圈

 

  - 與迴圈一起使用else
    for i in range(0, 5):
      print(i, end=" ")
    else:
      print("迴圈結束")
    # -> 0 1 2 3 4 迴圈結束
    - 當迴圈完全結束後(不被break和cuntinue打斷)執行else中的代碼
    - else同樣適用於while迴圈


  - 使用zip()並行迭代
    numbers = [1, 2, 3, 4]
    words = ["one", "two", "three", "four"]
    days = ["Mon.", "Tues.", "Wed.", "Thur."]
    for number, word, day in zip(numbers, words, days):
      print(number, word, day)
  輸出:
    1 one Mon.
    2 two Tues.
    3 three Wed.
    4 four Thur.
  - zip()函數在長度最小的參數中的元素用完後自動停止,其他參數未使用的元素將被略去,除非手動擴充其他較短的參數長度
  - zip()函數的傳回值不是列表或元組,而是一個整合在一起的可迭代變數
    list(zip(words, days))
    # -> [(‘one‘, ‘Mon.‘), (‘two‘, ‘Tues.‘), (‘three‘, ‘Wed.‘), (‘four‘, ‘Thur.‘)]

 

本文參考書籍:[美]Bill Lubanovic 《Python語言及其應用》

Python代碼結構——順序、分支、迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.