跳到主要内容

第4章:Python 控制流

4.1 条件语句(if-elif-else)

条件语句用于根据不同的条件执行不同的代码块。

基本 if 语句

# 基本 if 语句
x = 10

if x > 0:
print("x is positive")

if-else 语句

# if-else 语句
x = -5

if x > 0:
print("x is positive")
else:
print("x is not positive")

if-elif-else 语句

# if-elif-else 语句
x = 0

if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")

嵌套 if 语句

# 嵌套 if 语句
x = 10

if x > 0:
print("x is positive")
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
else:
print("x is not positive")

条件表达式(三元运算符)

# 条件表达式
x = 10
result = "positive" if x > 0 else "non-positive"
print(result)

# 多个条件表达式
y = 5
result = "greater than 10" if y > 10 else "between 5 and 10" if y >= 5 else "less than 5"
print(result)

4.2 循环语句(for 循环)

for 循环用于遍历序列(如列表、元组、字符串)中的元素。

基本 for 循环

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

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

# 遍历元组
colors = ("red", "green", "blue")
for color in colors:
print(color)

# 遍历字典
person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
print(key, person[key])

for key, value in person.items():
print(key, value)

使用 range() 函数

# 使用 range()
for i in range(5):
print(i) # 0, 1, 2, 3, 4

# 指定起始值和结束值
for i in range(2, 5):
print(i) # 2, 3, 4

# 指定步长
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8

# 倒序
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1

遍历带索引的序列

# 使用 enumerate()
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)

# 从指定索引开始
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)

4.3 循环语句(while 循环)

while 循环用于在条件为真时重复执行代码块。

基本 while 循环

# 基本 while 循环
count = 0
while count < 5:
print(count)
count += 1

while-else 语句

# while-else 语句
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed")

无限循环

# 无限循环(需要使用 break 退出)
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")

4.4 循环控制

break 语句

break 语句用于跳出当前循环。

# 使用 break
for i in range(10):
if i == 5:
break
print(i)

# 嵌套循环中的 break
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)

continue 语句

continue 语句用于跳过当前循环的剩余部分,继续下一次循环。

# 使用 continue
for i in range(10):
if i % 2 == 0:
continue
print(i) # 只打印奇数

# 跳过特定值
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit == "cherry":
continue
print(fruit)

pass 语句

pass 语句是一个空操作,用于占位。

# 使用 pass
for i in range(5):
if i == 2:
pass # 占位,什么也不做
else:
print(i)

# 定义空函数
def my_function():
pass # 占位,等待实现

# 定义空类
class MyClass:
pass # 占位,等待实现

4.5 列表推导式

列表推导式是一种简洁的创建列表的方法。

基本列表推导式

# 基本列表推导式
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared) # [1, 4, 9, 16, 25]

# 带条件的列表推导式
even_squared = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squared) # [4, 16]

# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 复杂条件
numbers = range(10)
result = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(result) # ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

字典推导式

# 字典推导式
numbers = [1, 2, 3, 4, 5]
squared_dict = {x: x ** 2 for x in numbers}
print(squared_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 带条件的字典推导式
even_squared_dict = {x: x ** 2 for x in numbers if x % 2 == 0}
print(even_squared_dict) # {2: 4, 4: 16}

集合推导式

# 集合推导式
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squared = {x ** 2 for x in numbers}
print(unique_squared) # {1, 4, 9, 16}

4.6 综合示例

示例1:猜数字游戏

import random

number = random.randint(1, 100)
guess = 0
attempts = 0

print("Guess the number between 1 and 100!")

while guess != number:
guess = int(input("Enter your guess: "))
attempts += 1

if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")

示例2:计算斐波那契数列

# 计算前 n 个斐波那契数
n = 10
fibonacci = [0, 1]

if n <= 2:
print(fibonacci[:n])
else:
for i in range(2, n):
next_number = fibonacci[i-1] + fibonacci[i-2]
fibonacci.append(next_number)
print(fibonacci)

示例3:打印乘法表

# 打印 9x9 乘法表
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j} × {i} = {i*j}", end="\t")
print()

4.7 常见问题和解决方案

问题1:无限循环

# 错误示例
count = 0
while count < 5:
print(count) # 缺少 count += 1

# 解决方案
count = 0
while count < 5:
print(count)
count += 1

问题2:缩进错误

# 错误示例
for i in range(5):
print(i) # 缺少缩进

# 解决方案
for i in range(5):
print(i) # 正确缩进

问题3:条件表达式错误

# 错误示例
if x = 5: # 使用了赋值运算符 = 而不是比较运算符 ==
print("x is 5")

# 解决方案
if x == 5: # 使用比较运算符 ==
print("x is 5")

4.8 练习

  1. 条件练习:编写一个程序,判断一个年份是否是闰年
  2. 循环练习:编写一个程序,打印 1 到 100 之间的所有质数
  3. 列表推导式练习
    • 创建一个列表,包含 1 到 10 的平方
    • 创建一个列表,包含 1 到 100 之间的所有偶数
    • 创建一个列表,包含字符串列表中长度大于 3 的字符串
  4. 综合练习:编写一个程序,模拟一个简单的计算器,支持加减乘除操作
  5. 挑战练习:编写一个程序,使用循环和条件语句,打印以下图案:
    *
    **
    ***
    ****
    *****

4.9 小结

本章我们学习了:

  • 条件语句(if-elif-else)
  • 循环语句(for 循环)
  • 循环语句(while 循环)
  • 循环控制(break、continue、pass)
  • 列表推导式、字典推导式和集合推导式
  • 综合示例

现在你已经掌握了 Python 的控制流,可以开始学习 Python 的函数了!