
理解循环的本质
循环是一种控制流机制,允许您根据特定条件重复执行代码块。python 提供了两种主要的循环类型:for 循环和 while 循环。
-
for循环:用于遍历序列,例如列表或元组。它从序列开头开始,并逐一遍历每个元素,直到到达末尾。 -
while循环:用于重复执行代码块,直到满足特定条件为止。它不断评估条件表达式,并在条件为True时执行代码块。立即学习“Python免费学习笔记(深入)”;
for 循环
for 循环的语法如下:
for item in sequence: # 代码块
其中:
-
item是循环中的局部变量,用于存储序列的当前元素。 -
sequence是您要遍历的序列。
演示代码:
colors = ["red", "blue", "green"]
for color in colors:
print(f"The color is {color}")
# 输出:
# The color is red
# The color is blue
# The color is green
while 循环
while 循环的语法如下:
while condition: # 代码块
其中:
-
condition是一个布尔表达式,用于确定是否重复执行代码块。
演示代码:
count = 1
while count <= 10:
print(f"Current count: {count}")
count += 1
# 输出:
# Current count: 1
# Current count: 2
# ...
# Current count: 10
高级用法
除了基本用法外,Python 循环还有以下高级用法:
-
break语句:用于立即退出循环。 -
continue语句:用于跳过当前迭代并继续执行下一个迭代。 - 迭代器:可用于自定义循环行为并遍历各种数据结构。
迭代器的作用
迭代器在 Python 循环中起着至关重要的作用。迭代器是一个对象,它可以在其元素上提供一个可遍历的接口。当您使用 for 循环时,底层会自动调用迭代器方法来获取序列的元素。
演示代码:
class MyRange: def __init__(self, start, end): self.start = start self.end = end def __iter__(self): current = self.start while current < self.end: yield current current += 1 for number in MyRange(1, 10): print(number) # 输出: # 1 # 2 # ... # 9
结论
Python 循环是强大的工具,用于控制程序流程和处理数据。通过理解 for 循环和 while 循环的本质,并利用高级用法和迭代器,您可以编写高效且可维护的代码。掌握 Python 循环的精髓,将显着提升您的编程技能。











