在Python中,for循环用于迭代一个可迭代对象(如列表、元组、字符串等)中的元素。
语法结构:
for 变量 in 可迭代对象: # 循环体代码
示例:
- 遍历列表中的元素
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
输出:
apple banana cherry
- 遍历字符串中的字符
message = 'Hello, World!' for char in message: print(char)
输出:
H e l l o , W o r l d !
- 使用range()函数生成一个数字序列进行迭代
for i in range(5): print(i)
输出:
1 2 3 4
在循环体内部,可以进行任何需要重复执行的操作,例如条件判断、函数调用等。可以使用break
关键字提前结束循环,或使用continue
关键字跳过当前迭代。