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