python迴圈語句筆記

來源:互聯網
上載者:User

標籤:int   nbsp   python迴圈   需要   序列   大於   ati   while   python   

while 迴圈語句

while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:

while 判斷條件:    執行語句……

執行語句可以是單個語句或語句塊。判斷條件可以是任何錶達式,任何非零、或非空(null)的值均為true。

當判斷條件假false時,迴圈結束。

while 語句時還有另外兩個重要的命令 continue,break 來跳過迴圈,continue 用於跳過該次迴圈,break 則是用於退出迴圈,此外"判斷條件"還可以是個常值,表示迴圈必定成立,具體用法如下:

# -*- coding: utf-8 -*-i = 1while i < 10:       i += 1    if i%2 > 0:     # 非雙數時跳過輸出        continue    print i         # 輸出雙數2、4、6、8、10 i = 1while 1:            # 迴圈條件為1必定成立    print i         # 輸出1~10    i += 1    if i > 10:     # 當i大於10時跳出迴圈        break

for 迴圈語句

for迴圈可以遍曆任何序列的項目,如一個列表或者一個字串。

for iterating_var in sequence:   statements(s)
# -*- coding: UTF-8 -*- for i in ‘Python‘:   print  i

輸出結果如下:

Python

迴圈使用 else 語句

在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區別,else 中的語句會在迴圈正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。

 

pass 語句

pass 不做任何事情,一般用做佔位語句。

# -*- coding: UTF-8 -*- for i in ‘Python‘:   if i == ‘h‘:      pass      print ‘pass‘   print  i

輸出結果如下:

Pytpasshon

 

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.