Python 循環(huán)嵌套

2021-09-03 17:17 更新

Python 循環(huán)嵌套

Python 語言允許在一個(gè)循環(huán)體里面嵌入另一個(gè)循環(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í)例使用了嵌套循環(huán)輸出 2~100 之間的素?cái)?shù):

#!/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 "{} 是素?cái)?shù)".format(i)
   i = i + 1

print "Good bye!"

以上實(shí)例輸出結(jié)果:

2 是素?cái)?shù)

3 是素?cái)?shù)

5 是素?cái)?shù)

7 是素?cái)?shù)

11 是素?cái)?shù)

13 是素?cái)?shù)

17 是素?cái)?shù)

19 是素?cái)?shù)

23 是素?cái)?shù)

29 是素?cái)?shù)

31 是素?cái)?shù)

37 是素?cái)?shù)

41 是素?cái)?shù)

43 是素?cái)?shù)

47 是素?cái)?shù)

53 是素?cái)?shù)

59 是素?cái)?shù)

61 是素?cái)?shù)

67 是素?cái)?shù)

71 是素?cái)?shù)

73 是素?cái)?shù)

79 是素?cái)?shù)

83 是素?cái)?shù)

89 是素?cái)?shù)

97 是素?cái)?shù)

Good bye!


更多實(shí)例

實(shí)例一:使用循環(huán)嵌套來獲取 100 以內(nèi)的質(zhì)數(shù)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

num=[];
i=2
for i in range(2,100):
   j=2
   for j in range(2,i):
      if(i%j==0):
         break
   else:
      num.append(i)
print num

運(yùn)行結(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]

實(shí)例二:使用嵌套循環(huán)實(shí)現(xiàn)*字塔的實(shí)現(xiàn)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#*字塔
i=1
#j=1
while i<=9:
   if i<=5:
      print "*"*i

   elif i<=9 :
      j=i-2*(i-5)
      print "*"*j 
   i+=1
else :
   print ""

運(yùn)行結(jié)果:

*

**

***

****

*****

****

***

**

*


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)