How to use for loops in Python?
The for loop in Python is used to iterate over an iterable object (such as a list, tuple, string, etc.) and perform specific operations.
The grammar format is as follows:
for 变量 in 可迭代对象:
# 执行操作
In each iteration, a variable is taken from the iterable object to be traversed, the iterable object is the object being traversed, and the operation is the code block to be executed in each iteration.
Here are some examples of using for loops:
- Iterating through a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
- Iterate through the string.
message = "Hello, World!"
for char in message:
print(char)
Output:
H
e
l
l
o
,
W
o
r
l
d
!
- Iterate through the dictionary.
student = {"name": "Alice", "age": 18, "grade": "A"}
for key in student:
print(key, "=", student[key])
Output:
name = Alice
age = 18
grade = A
- Looping with the range() function:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Here is the basic usage of a for loop, you can add conditional statements, nested loops, etc. within the loop based on specific requirements.