This article mainly introduces the nested use of circular statements in Python, which is the basic knowledge in Python, and the friends who need it can refer to the following
The Python programming language allows another loop to be nested within one loop. A few examples are presented below to illustrate this concept.
Grammar
The syntax for nested loop statements in Python is as follows:
?
1 2 3 4 |
For Iterating_var in Sequence:for Iterating_var in sequence:statements (s) statements (s) |
The Python programming language allows another loop to be nested within one loop. A few examples are presented below to illustrate this concept.
Grammar
The syntax for nested loop statements in Python is as follows:
?
1 2 3 4 |
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, as follows:
?
1 2 3 4 |
While Expression:while Expression:statement (s) statement (s) |
At the end of loop nesting it is necessary to describe any type of loop within any other type of loop. For example, a while loop can be placed within a for loop, and vice versa.
Example
The following program uses a nested loop to find all the primes from 2 to 100:
?
1 2 3 4 5 6 7 8 9 10 11-12 |
#!/usr/bin/python i = 2 while (I < m): J = 2 while (j <= (i/j)): If Not (I%J): Break J = j + 1 if (J > i/j): PR int I, "is prime" i = i + 1 print "Good bye!" |
When the above code is executed, it produces the following results:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
2 is prime 3 are prime 5 is prime 7 is prime one is prime I-Prime is prime-prime-is-prime-is-prime-the-is-is------------------ The is prime the prime is prime-is prime-is-prime-is-prime-is-prime-is-is-is-is-prime- |