循環使用 else 語句
在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區別,else 中的語句會在循環正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。
#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"
以上實例輸出結果為:
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
簡單語句組
類似if語句的語法,如果你的while循環體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:
#!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"
注意:以上的無限循環你可以使用 CTRL+C 來中斷循環。
Python 循環嵌套
Python 語言允許在一個循環體里面嵌入另一個循環。
Python for 循環嵌套語法:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
Python while 循環嵌套語法:
while expression: while expression: statement(s) statement(s)
你可以在循環體內嵌入其他的循環體,如在while循環中可以嵌入for循環, 反之,你可以在for循環中嵌入while循環。
實例:
以下實例使用了嵌套循環輸出2~100之間的素數:#!/usr/bin/python
# -*- coding: UTF-8 -*- i = 2 while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j) : print i, " 是素數" i = i + 1 print "Good bye!"
以上實例輸出結果:
2 是素數 3 是素數 5 是素數 7 是素數 11 是素數 13 是素數 17 是素數 19 是素數 23 是素數 29 是素數 31 是素數 37 是素數 41 是素數 43 是素數 47 是素數 53 是素數 59 是素數 61 是素數 67 是素數 71 是素數 73 是素數 79 是素數 83 是素數 89 是素數 97 是素數 Good bye!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
