python编程语言允许在一个循环内嵌套另一个循环。下面将介绍几个例子来说明这一概念。
语法
在python中嵌套循环语句的语法如下:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
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/pythoni = 2while(i < 100): j = 2 while(j i/j) : print i, is prime i = i + 1print good bye!
当执行上面的代码,它会产生以下结果:
2 is prime3 is prime5 is prime7 is prime11 is prime13 is prime17 is prime19 is prime23 is prime29 is prime31 is prime37 is prime41 is prime43 is prime47 is prime53 is prime59 is prime61 is prime67 is prime71 is prime73 is prime79 is prime83 is prime89 is prime97 is primegood bye!