詳解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)。
實例:
以下實例使用了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!'
以上實例輸出結(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. 什么是python的自省2. php模擬實現(xiàn)斗地主發(fā)牌3. vue 使用localstorage實現(xiàn)面包屑的操作4. spring acegi security 1.0.0 發(fā)布5. 理解PHP5中static和const關(guān)鍵字6. Python random庫使用方法及異常處理方案7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實現(xiàn)8. Vuex localStorage的具體使用9. MyBatis中的JdbcType映射使用詳解10. jQuery 實現(xiàn)DOM元素拖拽交換位置的實例代碼

網(wǎng)公網(wǎng)安備