在Python中,`for`循环用于遍历序列(如列表、元组、字典、字符串)或其他可迭代对象。以下是`for`循环的基本语法:
for iterating_var in sequence:
循环体,将要执行的代码块
`iterating_var`:在每次迭代中赋值的临时变量。
`sequence`:要遍历的序列或可迭代对象。
示例
遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
遍历字符串
word = 'python'
for letter in word:
print(letter)
使用`range()`函数
for i in range(5):
print(i)
遍历字典
dictionary = {'a': 1, 'b': 2, 'c': 3}
for key in dictionary:
print(key, dictionary[key])
包含`else`子句的`for`循环
for i in range(10):
if i == 5:
break
else:
print("Loop finished without breaking")
以上是Python中`for`循环的基本用法。