循環使用 else 語句
在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區別,else 中的語句會在循環正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。
#!/usr/bin/pythoncount = 0while count < 5: print count, " is less than 5" count = count + 1else: print count, " is not less than 5"
以上實例輸出結果為:
0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5
簡單語句組
類似if語句的語法,如果你的while循環體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:
#!/usr/bin/pythonflag = 1while (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 = 2while(i < 100):j = 2while(j <= (i/j)):if not(i%j): breakj = j + 1if (j > i/j) : print i, " 是素數"i = i + 1print "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!
新聞熱點
疑難解答
圖片精選