在Python中,使用for-in循環的基本語法是:
for 變量 in 可迭代對象:
# 循環體代碼
其中,可迭代對象
是一個序列(如列表、元組、字符串)或者一個可迭代的對象(如字典、集合),變量
是每次循環時取出的值。
以下是幾個for-in循環的示例:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
text = "Hello"
for letter in text:
print(letter)
person = {"name": "Alice", "age": 25}
for key in person:
print(key)
person = {"name": "Alice", "age": 25}
for value in person.values():
print(value)
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, value)
希望這些示例能幫助你理解如何在Python中使用for-in循環。