位置:首頁 > 腳本語言 > Python教學 > Python嵌套循環

Python嵌套循環

Python編程語言允許在一個循環內嵌套另一個循環。下麵將介紹幾個例子來說明這一概念。

語法

在Python中嵌套循環語句的語法如下:

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python編程語言的一個嵌套while循環語句的語法,如下所示:

while expression:
   while expression:
      statement(s)
   statement(s)

在循環嵌套最後需要說明的是,可以把任何類型的循環的任何其他類型的循環裡麵。例如,for循環內可以放置while循環,反之亦然。

例子

下麵的程序使用一個嵌套的循環,從2到100中找出所有的素數:

#!/usr/bin/python

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, " is prime"
   i = i + 1

print "Good bye!"

當執行上麵的代碼,它會產生以下結果:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!