Detailed Python loop nesting

The Python language allows embedding another loop inside a loop body.

**Python for loop nesting 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 other loops in the loop body, for example, you can embed a for loop in a while loop, otherwise, you can embed a while loop in a for loop.

**Example: **

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

#! /usr/bin/python
# - *- coding: UTF-8-*-
 
i =2while(i <100):
 j =2while(j <=(i/j)):ifnot(i%j):break
 j = j +1if(j   i/j): print i,"Is prime"
 i = i +1
 
print "Good bye!"

The output of the above example:

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!

Use for loop nesting to get prime numbers within 100

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

num=[];
i=2for i inrange(2,100):
 j=2for j inrange(2,i):if(i%j==0):breakelse:
 num.append(i)print(num)

Output result

[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]

Recommended Posts

Detailed Python loop nesting
Python exit loop
Detailed Python IO programming
05. Python entry value loop statement
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Python embeds C/C++ for detailed development
Detailed sorting algorithm (implemented in Python)
Python error handling assert detailed explanation
Detailed usage of dictionary in Python
Detailed tutorial on installing python3.7 for ubuntu18
Detailed explanation of Python IO port multiplexing
Detailed analysis of Python garbage collection mechanism
Python from attribute to property detailed explanation
Detailed usage of Python virtual environment venv
Detailed explanation of -u parameter of python command
Detailed explanation of Python guessing algorithm problems