Python循环逻辑错误:for和while的使用范例

原创 约定不等于承诺〃 2025-01-07 07:00 55阅读 0赞

在 Python 中,forwhile 是两种常用的循环结构。下面分别举例说明它们的使用:

  1. for循环:
    这是一种遍历序列(如列表、元组)或其他可迭代对象元素的方式。
  1. # 遍历列表
  2. fruits = ['apple', 'banana', 'orange']
  3. for fruit in fruits:
  4. print(fruit) # 输出:apple, banana, orange
  5. # 遍历元组
  6. coordinates = ((1, 2), (3, 4)))
  7. for point in coordinates:
  8. x, y = point # 分离坐标点
  9. print(f'Point ({x}, {y}))') # 输出:Point (1, 2)), Point (3, 4))
  1. while循环:
    这种循环在满足某个条件时一直执行。
  1. # 计数器示例
  2. count = 0
  3. while count < 5:
  4. print(f'Count: {count}') # 输出:Count: 0, Count: 1, Count: 2, Count: 3
  5. count += 1
  6. # 停止计数器
  7. if count == 5:
  8. print("Count limit reached. Loop stopped.")

总结一下,Python 中的 for 循环用于遍历序列,而 while 循环则是在满足某个条件时持续执行。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,55人围观)

还没有评论,来说两句吧...

相关阅读