python迴圈,判斷及函數

來源:互聯網
上載者:User

標籤:

  • python中的for迴圈
 
  1. #for迴圈格式(類似Java中的foreach):for 標識符 in 列表名稱 :
  2. >>> movies = ["movie1","movie2","movie3"]
  3. >>> for item in movies :
  4. print(item)
  5. movie1
  6. movie2
  7. movie3
python中的for迴圈類似Java中的foreach迴圈,固定格式見注釋其中:for表示迴圈開始,要出現在標識符前面;in將要迴圈的列表與標識符分隔開;:放在列表名後面,表示處理列表代碼開始;請注意,列表處理代碼必須放在for迴圈下面並縮排!!!當for迴圈開始時,python會將列表中的每一個值分別賦給標識符,這也意味著每次迴圈標識符的值都不一樣;迴圈會一直迭代,直到處理完列表中的所有資料。
  • python中的while迴圈
 
  1. #while迴圈格式:while 迴圈條件 :
  2. >>> while count < len(movies) :
  3. print(movies[count])
  4. count = count + 1
  5. movie1
  6. movie2
  7. movie3
while迴圈與for迴圈相比,多了條件判斷的語句,既可以自訂迴圈結束的條件
  • python的判斷
if-else格式
 
  1. if 滿足某個條件 :
  2. 執行某些語句
  3. else :
  4. 執行某些語句
注意:if語句與else語句最後都要加上:,且if與else後面要執行的代碼都要縮排
  • python的函數
 
  1. >>> new_movies = ["movie1","movie2","movie3",["movie4_1","movie4_2",["movie_4_3_1","movie_4_3_2"]],"movie5"]
  2. >>> def listItems(items) :
  3. for item in items :
  4. if isinstance(item,list) :
  5. listItems(item)
  6. else :
  7. print(item)
  8. >>> listItems(new_movies)
  9. movie1
  10. movie2
  11. movie3
  12. movie4_1
  13. movie4_2
  14. movie_4_3_1
  15. movie_4_3_2
  16. movie5



來自為知筆記(Wiz)

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.