詳解Python 循環(huán)嵌套
Python 語言允許在一個循環(huán)體里面嵌入另一個循環(huán)。
Python for 循環(huán)嵌套語法:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
Python while 循環(huán)嵌套語法:
while expression: while expression: statement(s) statement(s)
你可以在循環(huán)體內(nèi)嵌入其他的循環(huán)體,如在while循環(huán)中可以嵌入for循環(huán), 反之,你可以在for循環(huán)中嵌入while循環(huán)。
實(shí)例:
以下實(shí)例使用了while循環(huán)嵌套輸出2~100之間的素數(shù):
#!/usr/bin/python# -*- coding: UTF-8 -*- i = 2while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j) : print i, ' 是素數(shù)' i = i + 1 print 'Good bye!'
以上實(shí)例輸出結(jié)果:
2 是素數(shù)3 是素數(shù)5 是素數(shù)7 是素數(shù)11 是素數(shù)13 是素數(shù)17 是素數(shù)19 是素數(shù)23 是素數(shù)29 是素數(shù)31 是素數(shù)37 是素數(shù)41 是素數(shù)43 是素數(shù)47 是素數(shù)53 是素數(shù)59 是素數(shù)61 是素數(shù)67 是素數(shù)71 是素數(shù)73 是素數(shù)79 是素數(shù)83 是素數(shù)89 是素數(shù)97 是素數(shù)Good bye!
使用for循環(huán)嵌套來獲取100以內(nèi)的素數(shù)
#!/usr/bin/python# -*- coding: UTF-8 -*-num=[];i=2for i in range(2,100): j=2 for j in range(2,i): if(i%j==0): break else: num.append(i)print(num)
輸出結(jié)果
[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]
以上就是詳解Python 循環(huán)嵌套的詳細(xì)內(nèi)容,更多關(guān)于Python 循環(huán)嵌套的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP編碼必備的8條原則2. 使用css實(shí)現(xiàn)全兼容tooltip提示框3. 一文帶你搞懂JavaScript中的進(jìn)制與進(jìn)制轉(zhuǎn)換4. 匹配模式 - XSL教程 - 45. 詳解JS前端使用迭代器和生成器原理及示例6. 得到XML文檔大小的方法7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)9. ASP基礎(chǔ)知識Command對象講解10. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
