Python Nested Loops

Python language allows embedding another loop inside a loop body.

Python for nested loop syntax:

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

Python while nested loop syntax:

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

You can embed other loop bodies inside a loop body. For example, you can embed a for loop inside a while loop, and conversely, you can embed a while loop inside a for loop.

Example:

The following example uses nested loops to output prime numbers between 2 and 100:

Examples

#!/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 i, "is prime" i = i + 1 print "Good bye!"

The output of the above example is:

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 是素数
Good bye!
Other Extensions