Appearance
Python 循环语句
循环语句用于重复执行一段代码,直到满足特定条件为止。Python 提供了两种主要的循环语句:for 循环和 while 循环。本章节将详细介绍 Python 中的循环语句。
while 循环
while 循环用于在条件为真的情况下重复执行代码块。
基本语法
python
while condition:
# 条件为真时执行的代码块示例:
python
# while 循环示例
count = 1
while count <= 5:
print(f"计数:{count}")
count += 1
print("循环结束。")输出:
计数:1
计数:2
计数:3
计数:4
计数:5
循环结束。无限循环
如果 while 循环的条件始终为真,那么循环将无限执行下去,这就是无限循环。
示例:
python
# 无限循环示例(按 Ctrl+C 退出)
# count = 1
#
# while True:
# print(f"计数:{count}")
# count += 1
#
# print("循环结束。") # 这行代码永远不会执行break 语句
break 语句用于提前终止循环,跳出循环体。
示例:
python
# break 语句示例
count = 1
while count <= 10:
print(f"计数:{count}")
if count == 5:
print("遇到 break,提前终止循环。")
break
count += 1
print("循环结束。")输出:
计数:1
计数:2
计数:3
计数:4
计数:5
遇到 break,提前终止循环。
循环结束。continue 语句
continue 语句用于跳过当前循环的剩余部分,直接开始下一次循环。
示例:
python
# continue 语句示例
count = 0
while count < 10:
count += 1
if count % 2 == 0:
print(f"跳过偶数:{count}")
continue
print(f"计数:{count}")
print("循环结束。")输出:
计数:1
跳过偶数:2
计数:3
跳过偶数:4
计数:5
跳过偶数:6
计数:7
跳过偶数:8
计数:9
跳过偶数:10
循环结束。else 子句
while 循环可以带有一个 else 子句,当循环正常结束(即不是通过 break 语句终止)时,会执行 else 子句中的代码。
示例:
python
# while-else 语句示例
count = 1
while count <= 5:
print(f"计数:{count}")
count += 1
else:
print("循环正常结束,执行 else 子句。")
print("程序结束。")
# 使用 break 语句终止循环
print("\n使用 break 语句终止循环:")
count = 1
while count <= 5:
print(f"计数:{count}")
if count == 3:
print("遇到 break,提前终止循环。")
break
count += 1
else:
print("循环正常结束,执行 else 子句。") # 这行代码不会执行
print("程序结束。")输出:
计数:1
计数:2
计数:3
计数:4
计数:5
循环正常结束,执行 else 子句。
程序结束。
使用 break 语句终止循环:
计数:1
计数:2
计数:3
遇到 break,提前终止循环。
程序结束。for 循环
for 循环用于遍历可迭代对象(如列表、元组、字符串、字典等)中的元素。
基本语法
python
for item in iterable:
# 对每个元素执行的代码块示例:
python
# for 循环示例
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"水果:{fruit}")
print("循环结束。")输出:
水果:apple
水果:banana
水果:cherry
循环结束。遍历字符串
python
# 遍历字符串示例
text = "Hello, World!"
for char in text:
print(char, end=" ")
print("\n循环结束。")输出:
H e l l o , W o r l d !
循环结束。遍历元组
python
# 遍历元组示例
numbers = (1, 2, 3, 4, 5)
for num in numbers:
print(f"数字:{num}")
print("循环结束。")输出:
数字:1
数字:2
数字:3
数字:4
数字:5
循环结束。遍历字典
python
# 遍历字典示例
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 遍历字典的键
print("遍历字典的键:")
for key in person:
print(f"键:{key}")
# 遍历字典的值
print("\n遍历字典的值:")
for value in person.values():
print(f"值:{value}")
# 遍历字典的键值对
print("\n遍历字典的键值对:")
for key, value in person.items():
print(f"{key}: {value}")
print("循环结束。")输出:
遍历字典的键:
键:name
键:age
键:city
遍历字典的值:
值:Alice
值:30
值:New York
遍历字典的键值对:
name: Alice
age: 30
city: New York
循环结束。遍历 range() 函数
range() 函数用于生成一个整数序列,常用于 for 循环中。
语法:
python
range(start, stop, step)start:起始值(默认为 0)stop:结束值(不包含)step:步长(默认为 1)
示例:
python
# 遍历 range() 函数示例
# 基本用法
print("基本用法:")
for i in range(5):
print(f"i = {i}")
# 指定起始值和结束值
print("\n指定起始值和结束值:")
for i in range(2, 8):
print(f"i = {i}")
# 指定起始值、结束值和步长
print("\n指定起始值、结束值和步长:")
for i in range(1, 10, 2):
print(f"i = {i}")
# 反向遍历
print("\n反向遍历:")
for i in range(5, 0, -1):
print(f"i = {i}")
print("循环结束。")输出:
基本用法:
i = 0
i = 1
i = 2
i = 3
i = 4
指定起始值和结束值:
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
指定起始值、结束值和步长:
i = 1
i = 3
i = 5
i = 7
i = 9
反向遍历:
i = 5
i = 4
i = 3
i = 2
i = 1
循环结束。break 语句
for 循环中也可以使用 break 语句来提前终止循环。
示例:
python
# for 循环中的 break 语句示例
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
for fruit in fruits:
print(f"水果:{fruit}")
if fruit == "cherry":
print("遇到 break,提前终止循环。")
break
print("循环结束。")输出:
水果:apple
水果:banana
水果:cherry
遇到 break,提前终止循环。
循环结束。continue 语句
for 循环中也可以使用 continue 语句来跳过当前循环的剩余部分,直接开始下一次循环。
示例:
python
# for 循环中的 continue 语句示例
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
for fruit in fruits:
if fruit == "cherry":
print("跳过 cherry。")
continue
print(f"水果:{fruit}")
print("循环结束。")输出:
水果:apple
水果:banana
跳过 cherry。
水果:date
水果:elderberry
循环结束。else 子句
for 循环也可以带有一个 else 子句,当循环正常结束(即不是通过 break 语句终止)时,会执行 else 子句中的代码。
示例:
python
# for-else 语句示例
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"水果:{fruit}")
else:
print("循环正常结束,执行 else 子句。")
print("程序结束。")
# 使用 break 语句终止循环
print("\n使用 break 语句终止循环:")
for fruit in fruits:
print(f"水果:{fruit}")
if fruit == "banana":
print("遇到 break,提前终止循环。")
break
else:
print("循环正常结束,执行 else 子句。") # 这行代码不会执行
print("程序结束。")输出:
水果:apple
水果:banana
水果:cherry
循环正常结束,执行 else 子句。
程序结束。
使用 break 语句终止循环:
水果:apple
水果:banana
遇到 break,提前终止循环。
程序结束。嵌套循环
循环可以嵌套,即在一个循环内部再使用另一个循环。
示例:
python
# 嵌套循环示例
# 打印乘法表
print("乘法表:")
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j} × {i} = {i * j}", end="\t")
print()
print("\n循环结束。")
# 遍历二维列表
print("遍历二维列表:")
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num, end=" ")
print()
print("\n循环结束。")输出:
乘法表:
1 × 1 = 1
1 × 2 = 2 2 × 2 = 4
1 × 3 = 3 2 × 3 = 6 3 × 3 = 9
1 × 4 = 4 2 × 4 = 8 3 × 4 = 12 4 × 4 = 16
1 × 5 = 5 2 × 5 = 10 3 × 5 = 15 4 × 5 = 20 5 × 5 = 25
1 × 6 = 6 2 × 6 = 12 3 × 6 = 18 4 × 6 = 24 5 × 6 = 30 6 × 6 = 36
1 × 7 = 7 2 × 7 = 14 3 × 7 = 21 4 × 7 = 28 5 × 7 = 35 6 × 7 = 42 7 × 7 = 49
1 × 8 = 8 2 × 8 = 16 3 × 8 = 24 4 × 8 = 32 5 × 8 = 40 6 × 8 = 48 7 × 8 = 56 8 × 8 = 64
1 × 9 = 9 2 × 9 = 18 3 × 9 = 27 4 × 9 = 36 5 × 9 = 45 6 × 9 = 54 7 × 9 = 63 8 × 9 = 72 9 × 9 = 81
循环结束。
遍历二维列表:
1 2 3
4 5 6
7 8 9
循环结束。循环的应用场景
循环在编程中非常常见,以下是一些典型的应用场景:
- 遍历数据:遍历列表、元组、字符串等数据结构中的元素。
- 重复执行:重复执行一段代码,直到满足特定条件。
- 计数:从一个数开始,按照一定的步长递增或递减,直到达到目标值。
- 菜单驱动:显示菜单,根据用户的选择执行不同的功能,直到用户选择退出。
- 数据处理:处理大量数据,如计算总和、平均值、最大值、最小值等。
示例:
python
# 循环的应用场景
# 1. 遍历数据
print("1. 遍历数据")
students = ["Alice", "Bob", "Charlie", "David"]
for student in students:
print(f"学生:{student}")
# 2. 重复执行
print("\n2. 重复执行")
print("打印 'Hello' 5 次:")
for i in range(5):
print("Hello")
# 3. 计数
print("\n3. 计数")
print("从 1 数到 10:")
for i in range(1, 11):
print(i, end=" ")
print()
# 4. 菜单驱动
print("\n4. 菜单驱动")
while True:
print("\n菜单:")
print("1. 查看信息")
print("2. 修改信息")
print("3. 退出")
choice = input("请输入选项编号:")
if choice == "1":
print("查看信息...")
elif choice == "2":
print("修改信息...")
elif choice == "3":
print("退出程序...")
break
else:
print("无效的选项,请重新输入。")
# 5. 数据处理
print("\n5. 数据处理")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 计算总和
total = 0
for num in numbers:
total += num
print(f"总和:{total}")
# 计算平均值
average = total / len(numbers)
print(f"平均值:{average}")
# 找出最大值
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(f"最大值:{max_num}")
# 找出最小值
min_num = numbers[0]
for num in numbers:
if num < min_num:
min_num = num
print(f"最小值:{min_num}")
# 计算偶数的和
even_sum = 0
for num in numbers:
if num % 2 == 0:
even_sum += num
print(f"偶数的和:{even_sum}")总结
Python 中的循环语句包括 while 循环和 for 循环,用于重复执行一段代码。while 循环基于条件执行,for 循环基于遍历可迭代对象执行。此外,Python 还提供了 break、continue 语句以及 else 子句,用于控制循环的执行流程。掌握循环语句对于编写 Python 代码非常重要。