Python basic in... LOGIN
Python basic introductory tutorial
author:php.cn update time:2022-04-18 16:14:50

Python nested loops


The Python language allows you to embed another loop inside a loop body.

Python for loop nested 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 loop bodies within the loop body, such as a for loop within a while loop, Instead, you can embed a while loop inside a for loop.

Example:

The following example uses a nested loop to output prime numbers between 2 and 100:

#!/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 i, "is a prime number"
i = i + 1

print "Good bye!"

The above example output result:

2 is a prime number
3 Is a prime number
5 Is a prime number
7 Is a prime number
11 Is a prime number
13 Is a prime number
17 Is a prime number
19 Is a prime number
23 Is a prime number
29 Is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime number
Good bye!


php.cn