How to use a for loop in Python?
In Python, you can use a for loop to iterate through the elements of an iterable object (such as a list, tuple, string, etc.). The basic syntax of a for loop is as follows:
for 变量 in 可迭代对象:
# 执行的代码块
In this case, the variable is a temporary variable used to store the value of each element in every iteration. The iterable object is an object containing multiple elements.
Here are some common examples of using a for loop:
- Iterating through the elements in a list.
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
- Iterate through the characters in the string.
for char in 'Hello':
print(char)
Output:
H
e
l
l
o
- Create a sequence of numbers.
for num in range(1, 5):
print(num)
Output:
1
2
3
4
- create a list of items
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 orange
The above is the basic usage of a for loop, where you can perform different operations within the loop body based on specific requirements.