条件判断与循环结构详解

2 阅读5分钟

一、条件判断:if-elif-else

1.1 基础语法

# 简单的 if 判断
age = 18
if age >= 18:
    print("你已成年")

# if-else 结构
score = 75
if score >= 60:
    print("及格")
else:
    print("不及格")

# if-elif-else 多分支
grade = 85
if grade >= 90:
    print("优秀")
elif grade >= 80:
    print("良好")
elif grade >= 60:
    print("及格")
else:
    print("不及格")

1.2 条件表达式

Python 支持多种比较和逻辑运算符:

# 比较运算符
x = 10
y = 20

print(x == y)  # False (等于)
print(x != y)  # True (不等于)
print(x < y)   # True (小于)
print(x <= y)  # True (小于等于)
print(x > y)   # False (大于)
print(x >= y)  # False (大于等于)

# 逻辑运算符
a = True
b = False

print(a and b)  # False (与)
print(a or b)   # True (或)
print(not a)    # False (非)

# 成员运算符
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)      # True
print("grape" not in fruits)  # True

1.3 三元表达式

Python 支持简洁的条件表达式:

# 传统写法
age = 20
if age >= 18:
    status = "成年"
else:
    status = "未成年"

# 三元表达式
status = "成年" if age >= 18 else "未成年"
print(status)  # 成年

# 实际应用
price = 100
discount = 0.8 if price > 50 else 1.0
final_price = price * discount
print(f"最终价格:{final_price}")  # 最终价格:80.0

二、循环结构

2.1 for 循环

for 循环用于遍历序列(列表、元组、字符串等)或可迭代对象:

# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(f"我喜欢吃{fruit}")

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

# 使用 range() 函数
for i in range(5):      # 0 到 4
    print(i)

for i in range(2, 6):   # 2 到 5
    print(i)

for i in range(0, 10, 2):  # 0 到 9,步长为 2
    print(i)  # 0, 2, 4, 6, 8

2.2 while 循环

while 循环在条件为 True 时持续执行:

# 基础 while 循环
count = 0
while count < 5:
    print(f"计数:{count}")
    count += 1

# 实际应用:用户输入验证
password = ""
while password != "123456":
    password = input("请输入密码:")
    if password != "123456":
        print("密码错误,请重试")
print("登录成功!")

三、循环控制语句

3.1 break:跳出循环

# 找到第一个能被 7 整除的数
for i in range(1, 20):
    if i % 7 == 0:
        print(f"找到目标:{i}")
        break  # 找到后立即退出循环

# while 中的 break
num = 0
while True:
    print(num)
    num += 1
    if num >= 5:
        break

3.2 continue:跳过本次迭代

# 打印 1-10 中的奇数
for i in range(1, 11):
    if i % 2 == 0:
        continue  # 跳过偶数
    print(i)  # 1, 3, 5, 7, 9

# 跳过特定元素
names = ["Alice", "Bob", "Charlie", "David"]
for name in names:
    if name == "Bob":
        continue
    print(f"你好,{name}!")

3.3 else 子句

循环的 else 子句在循环正常结束(非 break 退出)时执行:

# 检查数字是否为质数
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            break
    else:
        return True  # 没有被整除,是质数
    return False

print(is_prime(7))   # True
print(is_prime(10))  # False

四、嵌套循环

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

# 输出:
# 1×1=1
# 1×2=2        2×2=4
# 1×3=3        2×3=6        3×3=9
# ...

五、实战案例

案例 1:猜数字游戏

import random

def guess_number():
    target = random.randint(1, 100)
    attempts = 0
    max_attempts = 7
    
    print("🎮 猜数字游戏开始!")
    print(f"我想了一个 1-100 的数字,你有{max_attempts}次机会")
    
    while attempts < max_attempts:
        try:
            guess = int(input(f"第{attempts + 1}次猜测:"))
            attempts += 1
            
            if guess == target:
                print(f"🎉 恭喜你!猜对了!答案就是{target}")
                break
            elif guess < target:
                print("📈 太小了!")
            else:
                print("📉 太大了!")
        except ValueError:
            print("❌ 请输入有效的数字!")
    else:
        print(f"😔 游戏结束!正确答案是{target}")

# 运行游戏
# guess_number()

案例 2:列表过滤与转换

# 过滤出偶数并计算平方
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 传统方法
even_squares = []
for num in numbers:
    if num % 2 == 0:
        even_squares.append(num ** 2)
print(even_squares)  # [4, 16, 36, 64, 100]

# 列表推导式(更 Pythonic)
even_squares = [num ** 2 for num in numbers if num % 2 == 0]
print(even_squares)  # [4, 16, 36, 64, 100]

案例 3:统计文本中的字符

def analyze_text(text):
    """统计文本中的字母、数字和其他字符"""
    letters = 0
    digits = 0
    others = 0
    
    for char in text:
        if char.isalpha():
            letters += 1
        elif char.isdigit():
            digits += 1
        else:
            others += 1
    
    return {
        "字母": letters,
        "数字": digits,
        "其他": others,
        "总计": len(text)
    }

# 测试
sample = "Python 3.11 发布了!"
result = analyze_text(sample)
for key, value in result.items():
    print(f"{key}: {value}")

六、最佳实践与常见陷阱

✅ 推荐做法

# 1. 使用 enumerate 获取索引和值
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# 2. 使用 zip 同时遍历多个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

# 3. 条件判断的简洁写法
# 不推荐
if is_valid == True:
    process()

# 推荐
if is_valid:
    process()

# 检查空列表
if len(my_list) > 0:  # 不推荐
    process()

if my_list:  # 推荐(空列表为 False)
    process()

❌ 常见陷阱

# 1. 在循环中修改列表
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # 危险!会跳过元素
print(numbers)  # [1, 3, 5] 但可能有问题

# 正确做法:创建新列表
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]
print(numbers)  # [1, 3, 5]

# 2. 忘记缩进
# if True:
# print("这会报错")  # IndentationError

# 3. 混淆 = 和 ==
x = 5
# if x = 5:  # 错误!这是赋值
if x == 5:   # 正确!这是比较
    print("x 等于 5")

七、今日总结

知识点关键内容
if-elif-else多分支条件判断
比较运算符==, !=, <, >, <=, >=
逻辑运算符and, or, not
for 循环遍历序列和 range()
while 循环条件持续执行
break立即退出循环
continue跳过本次迭代
else 子句循环正常结束时执行