在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循环。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: python的字符编码有哪些