Latest web development tutorials

Python nested loop

Python language allows embedded in a loop inside another loop.

Python for loop nested syntax:

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

Python while loop nested syntax:

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

You can embed in other loop the loop body, such as in the while loop can be embedded for loop, on the contrary, you can embed in a while loop for loop.

Example:

The following example uses a nested loop output prime number between 2 to 100:

#!/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, " 是素数"
   i = i + 1

print "Good bye!"

Examples of the above output:

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!