循环控制:Python for循环和while循环案例

原创 刺骨的言语ヽ痛彻心扉 2025-01-31 13:42 57阅读 0赞

在Python编程中,循环结构提供了反复执行代码块的方法。这里我们将介绍两种主要的循环类型:for循环和while循环。

  1. for循环

    • 适用于已知次数或长度的迭代。
    • 示例:

      1. # 遍历一个列表
      2. for item in ['apple', 'banana', 'cherry']:
      3. print(item)
      4. # 遍历一个字典
      5. dictionary = {'name': 'Tom', 'age': 20}
      6. for key, value in dictionary.items():
      7. print(f"{key}: {value}")
  2. while循环

    • 在循环条件满足时重复执行。
    • 示例:

      1. # 当数字小于10时循环
      2. count = 0
      3. while count < 10:
      4. print("This is loop number: ", count + 1)
      5. count += 1
      6. # 只要变量未改变,就一直循环
      7. variable = "change"
      8. while variable == "change":
      9. process()
      10. variable = input("Enter new value: ")

以上是Python中for循环和while循环的简单示例。在实际编程中,根据需要选择合适的循环类型。

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

发表评论

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

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

相关阅读