Python for Loop Statement
A Python for loop can iterate over the items of any sequence, such as a list or a string.
Syntax:
The syntax of a for loop is as follows:
for iterating_var in sequence:
statements(s)
Flow diagram:

Example:
Example
#!/usr/bin/python
-- coding: UTF-8 --
for
letter
in
'
Python
'
:
First Example
(
"
Current letter: %s
"
%
letter
)
fruits
=
[
'
banana
'
,
'
apple
'
,
'
mango
'
]
for
fruit
in
fruits
:
Second example
(
'
Current fruit: %s
'
%
fruit
)
(
"
Good bye!
"
)
Try it »
The output of the above example is:
当前字母: P
当前字母: y
当前字母: t
当前字母: h
当前字母: o
当前字母: n
当前水果: banana
当前水果: apple
当前水果: mango
Good bye!
Iterating Through Sequence Indices
Another way to perform loop traversal is by index, as in the following example:
Example
#!/usr/bin/python
-- coding: UTF-8 --
fruits
=
[
'
banana
'
,
'
apple
'
,
'
mango
'
]
for
index
in
range
(
len
(
fruits
)
)
:
(
'
Current fruit: %s
'
%
fruits
[
index
]
)
(
"
Good bye!
"
)
The example above produces the following output:
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!
In the above example we used the built-in functions len() and range(). The len() function returns the length of a list, that is, the number of elements. range returns a sequence of numbers.
Using the else Statement in Loops
In Python, for ... else means this: the statements in for are no different from ordinary ones, and the statements in else are executed when the loop finishes normally (that is, for is not interrupted by a break). The same applies to while ... else.
Example
#!/usr/bin/python
-- coding: UTF-8 --
for
num
in
range
(
10
,
20
)
:
Iterate over the numbers between 10 and 20 (exclusive)
for
i
in
range
(
2
,
num
)
:
Iterating by Factors
if
num
%
i
==
0
:
Determine the first factor
j
=
num
/
i
Calculate the second factor
(
'
%d is equal to %d * %d
'
%
(
num
,
i
,
j
)
)
break
Break out of the current loop
else
:
The else Part of the Loop
(
'
%d is a prime number
'
%
num
)
Try it »
The example above produces the following output:
10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数
More examples:Python printing diamonds, triangles, and rectangles