📅  最后修改于: 2023-12-03 15:30:50.300000             🧑  作者: Mango
In Python, a for
loop is used to iterate over a sequence (that can be a list, tuple, dictionary, string, set, range etc.) and perform the same action on each element in the sequence. The for
loop is an essential tool for any Python programmer.
The syntax of a for
loop in Python is as follows:
for var in sequence:
# code block to be executed for each value of var
Here, var
is the variable that takes on the value of each element in the sequence, one at a time. The sequence
can be any iterable object in Python.
# Print all the numbers from 0 to 9
for i in range(10):
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
In this example, range(10)
returns a sequence of numbers from 0 to 9, and the for
loop iterates over each value of i
in the sequence and prints it to the console.
In Python, it is possible to nest one for
loop inside another. This is useful when working with two-dimensional arrays or matrices, or when we want to perform an action on each element in a list of lists.
# Print all the elements in a 2D array
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for item in row:
print(item)
Output:
1
2
3
4
5
6
7
8
9
In this example, we have a 2D array of integers called matrix
. We use two nested for
loops to iterate over each element in the matrix and print it to the console.
The for
loop is a powerful tool in Python, and it is essential for any programmer to understand its syntax and usage. With the for
loop, we can iterate over sequences of elements and perform the same action on each element. We can also nest for
loops to work with two-dimensional arrays or perform more complex operations.