This article describes how to use nested loop statements in Python as an example. It is the basic knowledge in getting started with Python. If you need it, you can refer to the Python programming language to allow nesting of another loop in one loop. The following describes several examples to illustrate this concept.
Syntax
The syntax of nested loop statements in Python is as follows:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
The Python programming language allows nesting of another loop in one loop. The following describes several examples to illustrate this concept.
Syntax
The syntax of nested loop statements in Python is as follows:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
The syntax of a nested while LOOP statement in the Python programming language is as follows:
while expression: while expression: statement(s) statement(s)
At the end of loop nesting, it should be noted that any type of loop can be included in any other type of loop. For example, a while loop can be placed in a for loop, and vice versa.
Example
The following program uses a nested loop to find all prime numbers from 2 to 100:
#!/usr/bin/pythoni = 2while(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 + 1print "Good bye!"
When the above code is executed, it will produce the following results:
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!