Python 中的循环
循环是编程中的一种基本结构,用于重复执行一段代码。Python 提供了多种循环结构,包括 for
循环和 while
循环。此外,Python 还支持遍历可迭代对象(iterable),如列表、元组、字符串、字典等。
基本概念
for
循环:用于遍历序列(如列表、元组、字符串)或其他可迭代对象。while
循环:在条件为真时重复执行代码块。- 可迭代对象(iterable):可以被遍历的对象,如列表、元组、字符串、字典等。
示例讲解
让我们通过一些具体的例子来理解循环的用法。
示例1:for
循环
for
循环用于遍历序列或其他可迭代对象。
# 遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 遍历字符串
message = "Hello, World!"
for char in message:
print(char)
# 遍历范围
for i i