這篇文章主要介紹了舉例詳解Python中循環語句的嵌套使用,是Python入門中的基礎知識,需要的朋友可以參考下
Python編程語言允許在一個循環內嵌套另一個循環。下面將介紹幾個例子來說明這一概念。
語法
在Python中嵌套循環語句的語法如下:
?
1 2 3 4 for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)Python編程語言允許在一個循環內嵌套另一個循環。下面將介紹幾個例子來說明這一概念。
語法
在Python中嵌套循環語句的語法如下:
?
1 2 3 4 for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)Python編程語言的一個嵌套while循環語句的語法,如下所示:
?
1 2 3 4 while expression: while expression: statement(s) statement(s)在循環嵌套最後需要說明的是,可以把任何類型的循環的任何其他類型的循環裡面。例如,for循環內可以放置while循環,反之亦然。
例子
下面的程序使用一個嵌套的循環,從2到100中找出所有的素數:
?
1 2 3 4 5 6 7 8 9 10 11 12 #!/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!"當執行上面的代碼,它會產生以下結果:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 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!