Python循环逻辑错误:for和while的使用范例
在 Python 中,for
和 while
是两种常用的循环结构。下面分别举例说明它们的使用:
- for循环:
这是一种遍历序列(如列表、元组)或其他可迭代对象元素的方式。
# 遍历列表
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit) # 输出:apple, banana, orange
# 遍历元组
coordinates = ((1, 2), (3, 4)))
for point in coordinates:
x, y = point # 分离坐标点
print(f'Point ({x}, {y}))') # 输出:Point (1, 2)), Point (3, 4))
- while循环:
这种循环在满足某个条件时一直执行。
# 计数器示例
count = 0
while count < 5:
print(f'Count: {count}') # 输出:Count: 0, Count: 1, Count: 2, Count: 3
count += 1
# 停止计数器
if count == 5:
print("Count limit reached. Loop stopped.")
总结一下,Python 中的 for
循环用于遍历序列,而 while
循环则是在满足某个条件时持续执行。
还没有评论,来说两句吧...