在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循环。

