1. Python循环与判断基础概念

在Python编程中,循环和判断是构建程序逻辑的两大基石。它们就像交通信号灯和环形公路的关系——判断语句决定程序该往哪个方向走(if-else),而循环则让程序能够在特定条件下不断绕行(while/for),直到满足退出条件。

1.1 为什么需要循环与判断

想象你在写一个用户登录系统:

  • 需要判断用户输入的用户名密码是否正确(判断)
  • 如果错误要让用户重新输入(循环)
  • 连续错误5次则锁定账户(循环+判断)

没有这些控制结构,代码就只能线性执行,无法应对现实中的复杂逻辑。Python提供了以下几种核心控制结构:

结构类型 关键字 使用场景
条件判断 if/elif/else 根据条件执行不同代码块
循环 while 条件满足时重复执行
循环 for 遍历序列中的元素
循环控制 break/continue 中断循环或跳过当前迭代

1.2 基础语法对比

先看一个典型if判断结构:

age = 18
if age < 18:
    print("未成年")
elif age == 18:
    print("刚成年")
else:
    print("已成年")

而while循环的基本形式是:

count = 0
while count < 5:
    print(f"当前计数: {count}")
    count += 1

关键区别在于:

  • if判断只执行一次符合条件的代码块
  • while会反复执行直到条件不成立

2. 循环的深度解析

2.1 while循环的底层机制

while循环的执行流程可以用以下伪代码表示:

1. 评估condition表达式
2. 如果结果为True:
   a. 执行循环体
   b. 回到步骤1
3. 如果结果为False:
   a. 退出循环

实际内存中的执行过程:

  1. 创建condition的布尔上下文
  2. 生成循环代码块的栈帧
  3. 每次迭代都会:
    • 检查condition值
    • 执行栈帧中的字节码
    • 维护循环变量状态

2.2 避免无限循环的5个技巧

新手常犯的错误是创建无限循环。比如:

# 危险示例!
while True:
    print("无限循环")

安全实践应包括:

  1. 设置明确的退出条件

    max_retry = 3
    attempts = 0
    while attempts < max_retry:
        attempts += 1
    
  2. 添加超时机制

    import time
    start = time.time()
    while time.time() - start < 10:  # 10秒超时
        # 正常操作
    
  3. 使用break条件

    while True:
        user_input = input("输入q退出: ")
        if user_input == 'q':
            break
    
  4. 添加循环计数器保护

    safe_limit = 1000
    counter = 0
    while condition:
        counter += 1
        if counter > safe_limit:
            raise RuntimeError("循环超出安全限制")
    
  5. 异常捕获处理

    try:
        while risky_condition:
            # 可能失败的操作
    except SafetyException:
        print("安全机制触发")
    

3. 条件判断的高级用法

3.1 多条件组合判断

Python支持使用and/or/not组合多个条件:

age = 25
is_member = True

if age >= 18 and is_member:
    print("尊享会员服务")
elif age >= 65 or is_veteran:
    print("长者特别优惠")
elif not is_verified:
    print("请先完成认证")

真值表速查:

A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

3.2 优雅的条件表达式

对于简单的二选一场景,可以使用三元表达式:

# 传统写法
if score >= 60:
    result = "及格"
else:
    result = "不及格"

# 三元表达式
result = "及格" if score >= 60 else "不及格"

处理None值的简便写法:

# 传统None检查
if value is None:
    default_value = 0
else:
    default_value = value

# 更Pythonic的写法
default_value = value if value is not None else 0

4. 实战案例:猜数字游戏

4.1 基础版本实现

import random

def guess_number():
    secret = random.randint(1, 100)
    attempts = 0
    
    while True:
        guess = int(input("猜一个1-100的数字: "))
        attempts += 1
        
        if guess == secret:
            print(f"恭喜!你在{attempts}次尝试后猜对了")
            break
        elif guess < secret:
            print("猜小了,再试试")
        else:
            print("猜大了,再试试")

guess_number()

4.2 增强功能版

添加以下特性:

  1. 输入验证
  2. 尝试次数限制
  3. 游戏统计
import random

class NumberGuesser:
    def __init__(self):
        self.total_games = 0
        self.total_attempts = 0
    
    def validate_input(self, prompt, min_val, max_val):
        while True:
            try:
                value = int(input(prompt))
                if min_val <= value <= max_val:
                    return value
                print(f"请输入{min_val}-{max_val}之间的数字")
            except ValueError:
                print("请输入有效的整数")
    
    def play_game(self):
        secret = random.randint(1, 100)
        max_attempts = 10
        attempts = 0
        
        print("\n新游戏开始!你有10次机会")
        
        while attempts < max_attempts:
            attempts += 1
            guess = self.validate_input(
                f"尝试#{attempts}: 猜一个1-100的数字: ",
                1, 100
            )
            
            if guess == secret:
                print(f"太棒了!你在{attempts}次尝试后猜对了")
                self.total_games += 1
                self.total_attempts += attempts
                return True
            elif guess < secret:
                print("提示:猜小了")
            else:
                print("提示:猜大了")
        
        print(f"游戏结束,正确答案是{secret}")
        self.total_games += 1
        return False
    
    def show_stats(self):
        if self.total_games > 0:
            avg = self.total_attempts / self.total_games
            print(f"\n游戏统计:")
            print(f"总游戏数: {self.total_games}")
            print(f"平均尝试次数: {avg:.1f}")

# 使用示例
guesser = NumberGuesser()
while True:
    guesser.play_game()
    again = input("再玩一次?(y/n): ").lower()
    if again != 'y':
        guesser.show_stats()
        break

5. 性能优化与最佳实践

5.1 循环性能优化

  1. 避免在循环中重复计算

    # 不推荐
    while i < len(my_list):  # len()每次循环都会执行
        # ...
    
    # 推荐
    list_length = len(my_list)
    while i < list_length:
        # ...
    
  2. 使用for循环替代while遍历序列

    # while方式
    i = 0
    while i < len(items):
        print(items[i])
        i += 1
    
    # 更Pythonic的for方式
    for item in items:
        print(item)
    
  3. 利用生成器处理大数据集

    def large_dataset():
        for i in range(1000000):
            yield i  # 每次只生成一个值
    
    for num in large_dataset():  # 内存友好
        process(num)
    

5.2 条件判断优化技巧

  1. 短路求值原则

    • and操作:如果第一个条件为False,不会评估第二个
    • or操作:如果第一个条件为True,不会评估第二个

    利用这个特性可以优化判断:

    # 安全访问嵌套字典
    value = config.get('section', {}).get('key', default)
    
    # 等价于
    if 'section' in config and 'key' in config['section']:
        value = config['section']['key']
    else:
        value = default
    
  2. 尽早返回原则

    # 优化前
    def process_data(data):
        if valid_data(data):
            # 很长的处理逻辑
            return result
        else:
            return None
    
    # 优化后
    def process_data(data):
        if not valid_data(data):
            return None
        
        # 主要逻辑现在不需要缩进
        # ...
        return result
    
  3. 使用字典代替复杂if-elif链

    # 传统方式
    def handle_status(code):
        if code == 200:
            return "成功"
        elif code == 404:
            return "未找到"
        # ...
    
    # 字典映射方式
    def handle_status(code):
        status_map = {
            200: "成功",
            404: "未找到",
            500: "服务器错误"
        }
        return status_map.get(code, "未知状态码")
    
Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐