Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Nested Loops

Python Nested Loops

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

Syntax of nested Python for loops:

for

iterating_var

in

sequence

:

for

iterating_var

in

sequence

:

statements

(

s

)

statements

(

s

)

Syntax of nested Python while loops:

while

expression

:

while

expression

:

statement

(

s

)

statement

(

s

)

You can embed other loop bodies within a loop body. For example, you can embed a for loop inside a while loop; conversely, you can embed a while loop inside a for loop.

Example:

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

Example

#!/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 output of the above example is:


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 是素数
Good bye!