How do you write a for loop in Python?
The basic syntax of using a for-in loop in Python is:
for 变量 in 可迭代对象:
# 循环体代码
In this case, an iterable object is a sequence (such as a list, tuple, or string) or an iterable object (such as a dictionary or set), and the variable is the value extracted each time during the loop.
Here are some examples of for-in loops:
- Iterate through the list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- Iterate through the string.
text = "Hello"
for letter in text:
print(letter)
- Iterate through the keys of the dictionary.
person = {"name": "Alice", "age": 25}
for key in person:
print(key)
- Iterate over the values of a dictionary.
person = {"name": "Alice", "age": 25}
for value in person.values():
print(value)
- Iterating through the key-value pairs of a dictionary:
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, value)
I hope these examples can help you understand how to use for-in loops in Python.