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
语句用于提前终止循环。它可以在 for
或 while
循环中使用。
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
子句可以与 for
或 while
循环一起使用。当循环正常结束(没有遇到 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. 使用 enumerate
和 zip
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
循环。通过结合控制循环的语句(如 break
和 continue
)以及辅助函数(如 enumerate
和 zip
),可以非常灵活地控制循环的执行。