Python while迴圈

來源:互聯網
上載者:User

標籤:結束   bre   UI   pycharm   也會   proc   運算式   ==   continue   

while迴圈文法結構當需要語句不斷的重複執行時,可以使用while迴圈while expression:    while_suite語句while_suite會連續不斷的迴圈執行,直到運算式的值變成0或false 
#!/usr/bin/env pythonsum100 = 0counter = 1while counter <= 100:    sum100 += counter    counter += 1print "result is %d" % sum100
break語句break語句可以結束當前迴圈然後跳轉到下條語句寫程式的時候,應盡量避免重複的代碼,在這種情況下可以使用while-break結構
#!/usr/bin/env pythonwhile True:    yn = raw_input("continue?(y/n)")    if yn in ‘Yy‘:        break    print "work on"/usr/bin/python2.6 /root/PycharmProjects/untitled10/break1.pycontinue?(y/n)nwork oncontinue?(y/n)yProcess finished with exit code 0
continue語句當遇到continue語句時,程式會終止當前迴圈,並忽略剩餘的語句.然後回到迴圈的頂端如果仍然滿足迴圈條件,迴圈體內語句繼續執行,否則退出迴圈所有偶數的和
#!/usr/bin/env pythonsum100 = 0counter = 1while counter <= 100:    counter += 1    if counter % 2 == 1:        continue    sum100 += counterprint sum100
else語句python中的while語句也支援else子句else子句只在迴圈完成後執行break語句也會跳過else塊
#!/usr/bin/env pythonsum10 = 0i = 1while i <= 10:    sum10 += i    i += 1else:    print sum10

 

Python while迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.