Python for Loop
for is the most commonly used loop statement in Python, used to traverse iterables (sequences, dictionaries, sets, etc.).
Python's for The loop is more concise and powerful than in languages such as C/C++; there is no need to manage a loop variable manually, as elements are traversed directly.
Word meaning: for means "for", used for iterative traversal.
Basic syntax and parameters
Syntax format
for variable in iterable:
代码块
Syntax Description
- Variables: the element taken from the iterable on each iteration.
- Iterable objects: lists, tuples, strings, dictionaries, sets, range, etc.
- Indentation: the loop body must be indented.
else clause
- Optional: a for loop can have an else clause.
- Execution Timing: executes when the loop ends normally (not exited via break).
Example
Example 1: traversing a list
Example
Traverse the list
fruits
=
[
"Apple"
,
"Banana"
,
"Orange"
]
for
fruit
in
fruits:
(
fruit
)
Traversal with indexes
for
i
,
fruit
in
enumerate
(
fruits
)
:
(
f
"{i}: {fruit}"
)
Expected output:
苹果
香蕉
橙子
0: 苹果
1: 香蕉
2: 橙子
Code analysis:
- The for loop traverses each element in the list directly.
- enumerate() provides both the index and the value.
Example 2: traversing strings and tuples
Example
Traverse a string
for
char
in
"Python"
:
(
char
,
end
=
" "
)
(
)
Newline
Traverse a tuple
point
=
(
10
,
20
)
for
value
in
point:
(
value
,
end
=
" "
)
(
)
Expected output:
P y t h o n
10 20
Strings and tuples are also iterable.
Example 3: traversing a dictionary
Example
Traverse a dictionary (keys are traversed by default)
person
=
{
"name"
:
"Tom"
,
"age"
:
20
,
"city"
:
"Beijing"
}
for
key
in
person:
(
key
)
(
"---"
)
Traverse key/value pairs
for
key
,
value
in
person.
items
(
)
:
(
f
"{key}: {value}"
)
(
"---"
)
Traverse values only
for
value
in
person.
values
(
)
:
(
value
)
Expected output:
name
age
city
---
name: Tom
age: 20
city: Beijing
---
Tom
20
Beijing
The items(), keys(), and values() methods of a dictionary can traverse different parts.
Example 4: for loop with else
Example
for-else structure
for
i
in
range
(
3
)
:
(
i
)
else
:
(
"The loop ended normally"
)
(
"---"
)
else is not executed when break is used
for
i
in
range
(
5
)
:
if
i
==
3
:
break
(
i
)
else
:
(
"This line will not be printed"
)
Expected output:
0
1
2
循环正常结束
---
0
1
2
In a for-else structure, else is not executed when the loop is terminated by break.
Example 5: nested loops
Example
Nested loops - printing the multiplication table
for
i
in
range
(
1
,
10
)
:
for
j
in
range
(
1
,
i +
1
)
:
(
f
"{j}{i}={ij}"
,
end
=
"\t"
)
(
)
Expected output:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
...
Nested loops can handle multi-dimensional data structures or generate tables.
Python3 loop statements