Python 循环:for 循环和 while 循环详解
Python 循环:for 循环和 while 循环
Python 中有两种主要的循环结构:for 循环和 while 循环。
1. for 循环
for 循环用于遍历可迭代对象(如列表、元组、字符串等)中的元素,语法如下:
for 变量 in 可迭代对象:
循环体
示例:
fruits = ['apple', 'banana', 'cherry']
for x in fruits:
print(x)
输出:
apple
banana
cherry
2. while 循环
while 循环用于在条件为真的情况下重复执行某些代码,语法如下:
while 条件:
循环体
示例:
i = 1
while i < 6:
print(i)
i += 1
输出:
1
2
3
4
5
需要注意的是,在使用 while 循环时要确保有终止循环的条件,否则循环将永远执行下去。
原文地址: https://www.cveoy.top/t/topic/nPiQ 著作权归作者所有。请勿转载和采集!