【Python入门与进阶】Python的循环结构

Python 提供了几种循环结构,主要包括 for 循环和 while 循环。这些循环结构允许程序重复执行特定的代码块。以下是对 Python 循环结构的详细介绍和示例。

1. for 循环

for 循环用于遍历序列(如列表、元组、字符串)或其他可迭代对象。语法如下:

for variable in iterable:
    # 执行的代码块
示例
# 遍历列表
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

# 遍历字符串
for char in "hello":
    print(char)

# 使用 range() 函数
for i in range(5):
    print(i)

2. while 循环

while 循环在给定的条件为 True 时重复执行代码块。语法如下:

while condition:
    # 执行的代码块
示例
# 简单的 while 循环
count = 0
while count < 5:
    print(count)
    count += 1

3. 控制循环的语句

break

break 语句用于提前终止循环。它可以在 forwhile 循环中使用。

for i in range(10):
    if i == 5:
        break
    print(i)
continue

continue 语句跳过当前迭代,继续执行下一次循环。

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
else

else 子句可以与 forwhile 循环一起使用。当循环正常结束(没有遇到 break)时,执行 else 块。

for i in range(5):
    print(i)
else:
    print("循环结束")

# 使用 while 循环
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("循环结束")

4. 嵌套循环

循环可以嵌套使用,即在一个循环体内再包含一个循环。

for i in range(3):
    for j in range(2):
        print(f"i = {i}, j = {j}")

5. 使用 enumeratezip

enumerate

enumerate 函数用于在遍历序列时获取元素的索引和值。

words = ["hello", "world", "python"]
for index, word in enumerate(words):
    print(f"Index: {index}, Word: {word}")
zip

zip 函数用于并行遍历多个可迭代对象。

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

总结

循环结构是编程中重复执行任务的基本工具。在 Python 中,主要使用 for 循环和 while 循环。通过结合控制循环的语句(如 breakcontinue)以及辅助函数(如 enumeratezip),可以非常灵活地控制循环的执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值