Python控制流——条件与循环

学习目标

通过本集的学习,你将能够:

  • 使用 if/elif/else 语句进行条件判断
  • 使用 for 循环遍历序列
  • 使用 while 循环进行条件循环
  • 掌握 break 和 continue 语句的用法
  • 写出带有流程控制的程序

1. 条件语句:if/elif/else

条件语句让程序根据不同情况做出不同的选择。

1.1 基本 if 语句

# 基本if语句
age = 18

if age >= 18:
    print("你已经成年了")

流程图:

      开始
        │
        ▼
   age >= 18?
   ┌─────┴─────┐
   │ 是        │ 否
   ▼           ▼
 打印消息    什么都不做
   │           │
   └─────┬─────┘
         ▼
        结束

1.2 if-else 语句

# if-else语句
age = 16

if age >= 18:
    print("你已经成年了")
else:
    print("你还未成年")

1.3 if-elif-else 语句

# if-elif-else语句
score = 85

if score >= 90:
    grade = "优秀"
elif score >= 80:
    grade = "良好"
elif score >= 60:
    grade = "及格"
else:
    grade = "不及格"

print("成绩等级:", grade)  # 输出: 成绩等级: 良好

1.4 嵌套的 if 语句

# 嵌套的if语句
age = 20
has_license = True

if age >= 18:
    if has_license:
        print("你可以开车")
    else:
        print("你需要先考驾照")
else:
    print("你还未成年")

1.5 多个条件组合

# 使用and、or、not组合条件
age = 25
has_money = True
is_weekend = False

# and:所有条件都满足
if age >= 18 and has_money:
    print("你可以买这个东西")

# or:只要有一个条件满足
if is_weekend or age >= 18:
    print("你可以去玩")

# not:取反
if not is_weekend:
    print("今天要上班/上学")

2. for 循环

for 循环用于遍历序列(如列表、字符串等)。

2.1 基本 for 循环

# 遍历列表
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# 输出:
# apple
# banana
# cherry

流程图:

      开始
        │
        ▼
   还有元素吗?
   ┌─────┴─────┐
   │ 是        │ 否
   ▼           ▼
 处理元素     结束
   │
   └─────┐
         ▼
    回到检查

2.2 使用 range() 函数

# range(stop):从0开始
for i in range(5):
    print(i)
# 输出: 0, 1, 2, 3, 4

# range(start, stop):指定开始
for i in range(2, 7):
    print(i)
# 输出: 2, 3, 4, 5, 6

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

# 倒序
for i in range(10, 0, -1):
    print(i)
# 输出: 10, 9, 8, ..., 1

2.3 遍历字符串

# 遍历字符串中的每个字符
text = "Python"

for char in text:
    print(char)

# 输出:
# P
# y
# t
# h
# o
# n

2.4 遍历字典

# 遍历字典
student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}

# 遍历键
for key in student:
    print(key)

# 遍历键值对
for key, value in student.items():
    print(key, ":", value)

# 输出:
# name : Alice
# age : 20
# grade : A

3. while 循环

while 循环在条件满足时不断执行。

3.1 基本 while 循环

# 基本while循环
count = 0

while count < 5:
    print(count)
    count = count + 1

# 输出: 0, 1, 2, 3, 4

3.2 无限循环

# 无限循环(需要break来停止)
while True:
    user_input = input("输入 'quit' 退出: ")
    if user_input == "quit":
        break
    print("你输入了:", user_input)

3.3 使用 while 循环遍历列表

# 使用while循环遍历列表
fruits = ["apple", "banana", "cherry"]
index = 0

while index < len(fruits):
    print(fruits[index])
    index = index + 1

4. break 和 continue 语句

4.1 break:跳出循环

# break示例
for i in range(10):
    if i == 5:
        break  # 遇到5就跳出循环
    print(i)

# 输出: 0, 1, 2, 3, 4

break 流程图:

      开始
        │
        ▼
   i < 10?
   ┌─────┴─────┐
   │ 是        │ 否
   ▼           ▼
  i == 5?    结束
   ┌───┴───┐
   │ 是    │ 否
   ▼       ▼
  break   打印i
   │       │
   └───┬───┘
       ▼
   i = i + 1
       │
       ▼
   回到检查

4.2 continue:跳过本次循环

# continue示例
for i in range(10):
    if i == 5:
        continue  # 跳过5,继续下一次
    print(i)

# 输出: 0, 1, 2, 3, 4, 6, 7, 8, 9

5. 循环中的 else

# for循环的else
for i in range(5):
    print(i)
else:
    print("循环正常结束")

# while循环的else
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("循环正常结束")

# 如果循环被break中断,else不会执行
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("这个不会执行")

6. 实用案例

6.1 案例1:猜数字游戏

# guess_number.py
import random

secret_number = random.randint(1, 100)
attempts = 0

print("猜数字游戏!我想了一个1到100之间的数字。")

while True:
    guess = int(input("请猜一个数字: "))
    attempts += 1
    
    if guess < secret_number:
        print("太小了!")
    elif guess > secret_number:
        print("太大了!")
    else:
        print(f"恭喜!你猜对了!用了{attempts}次。")
        break

6.2 案例2:乘法表

# multiplication_table.py

# 打印九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        product = i * j
        print(f"{j}x{i}={product}", end="  ")
    print()

6.3 案例3:计算阶乘

# factorial.py

# 使用for循环计算阶乘
n = 5
result = 1

for i in range(1, n + 1):
    result = result * i

print(f"{n}! = {result}")  # 输出: 5! = 120

# 使用while循环计算阶乘
n = 5
result = 1
i = 1

while i <= n:
    result = result * i
    i = i + 1

print(f"{n}! = {result}")

6.4 案例4:斐波那契数列

# fibonacci.py

# 打印斐波那契数列
n_terms = 10
a, b = 0, 1
count = 0

while count < n_terms:
    print(a, end=" ")
    a, b = b, a + b
    count += 1

# 输出: 0 1 1 2 3 5 8 13 21 34

7. 自测问题

  1. if、elif、else 的执行顺序是什么?
  2. for 循环和 while 循环有什么区别?
  3. break 和 continue 有什么区别?
  4. 如何使用 range() 函数生成倒序序列?
  5. 循环中的 else 子句什么时候执行?

8. 下集预告

下一集我们将学习Python的函数!

参考资料

« 上一篇 Python快速入门——变量与数据类型 下一篇 » Python函数(上)