Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python loop nesting


May 10, 2021 Python2


Table of contents


Python loop nesting

The Python language allows another loop to be embedded in one loop body.

Python for loop nesting syntax:

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

Python while loop nesting syntax:

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

You can embed other loop bodies in the loop body, such as the for loop in the while loop, and instead, you can embed the while loop in the for loop.

Instance:

The following example uses a prime number between 2 and 100 of the nested loop output:

#!/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 ("{} 是素数".format(i))
   i = i + 1

print("Good bye!")

The above example output results:

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!

More instances

Example 1: Use circular nesting to get the number of masses within 100

#!/usr/bin/python
# -*- coding: UTF-8 -*-

num=[];
i=2
for i in range(2,100):
   j=2
   for j in range(2,i):
      if(i%j==0):
         break
   else:
      num.append(i)
print(num)

Example 2: Use nested loops to implement × of the word tower

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#*字塔
i=1
#j=1
while i<=9:
   if i<=5:
      print ("*"*i)

   elif i<=9 :
      j=i-2*(i-5)
      print("*"*j)
   i+=1
else :
   print("")