上一章我们学习了运算符,能够对数据进行计算和比较。但程序真正的“智能”来自于根据不同的条件执行不同的代码—就像 AI 模型根据你的输入内容决定如何回复,根据 token 数量决定是否截断,根据温度系数决定输出的随机程度。
本章将学习
if条件判断、else、elif,以及循环控制(for、while),所有例子都紧扣 AI 大模型的实际开发场景。
4.1 布尔表达式:条件判断的“是非题”
在正式学习if之前,你需要理解什么是“条件”。任何条件最终都会变成一个布尔值:True(真)或False(假)。
比较运算符和逻辑运算符产生的结果就是布尔值。
4.1.1 什么是布尔表达式?
简单说,就是一个可以回答“是”或“否”的问题。
temperature = 0.8 is_creative = temperature > 0.5 # True is_too_random = temperature > 1.5 # False model_name = "gpt-4" is_premium = (model_name == "gpt-4") # True在 AI 开发中,布尔表达式常用来:
检查 API 返回是否成功
判断生成文本是否包含禁忌词
验证用户输入是否符合格式
4.2 if 语句:如果……就……
if语句是最基本的流程控制,它的意思是:如果某个条件成立,就执行一段代码。
4.2.1 基本语法
if 条件: 条件成立时执行的代码块注意:
条件后面要加冒号
:代码块必须缩进(通常用 4 个空格),表示这行代码属于
if管辖
4.2.2 AI 场景实例
# 例1:检查 temperature 是否合法 temperature = 1.8 if temperature > 2.0: print("警告:温度超过最大值 2.0,模型输出可能不稳定!") # 例2:检查是否达到最大 token 限制 used_tokens = 3800 max_tokens = 4096 if used_tokens >= max_tokens: print("已达到上下文长度上限,将停止生成。") # 例3:检查 API 密钥是否存在 api_key = "" if api_key == "": print("错误:未设置 API 密钥,请检查环境变量。")💡 如果条件为
False,代码块会被跳过,什么也不执行。
4.3 if-else 语句:如果……否则……
if-else提供了两种选择:条件成立时做 A,不成立时做 B。
4.3.1 基本语法
if 条件: 条件成立时执行 else: 条件不成立时执行4.3.2 AI 场景实例
# 例1:根据 temperature 决定回复风格 temperature = 0.2 if temperature < 0.5: print("模型将采用确定性输出,答案更保守。") else: print("模型将引入更多随机性,答案更多样。") # 例2:检查模型是否支持函数调用 model_family = "gpt-3.5" if model_family == "gpt-4": print("支持函数调用和并行工具使用。") else: print("仅支持基本对话功能。") # 例3:判断是否需要截断提示词 prompt_length = 8500 max_context = 8192 if prompt_length > max_context: print(f"提示词过长,将自动截断至 {max_context} 字符。") else: print("提示词长度合适,无需截断。")4.4 if-elif-else 语句:多分支判断
当你有多个互斥的条件需要判断时,使用elif(else if 的缩写)。
4.4.1 基本语法
if 条件1: 条件1成立时执行 elif 条件2: 条件1不成立但条件2成立时执行 elif 条件3: 条件1、2都不成立但条件3成立时执行 else: 所有条件都不成立时执行你可以写任意多个elif,else是可选的。
4.4.2 AI 场景实例
# 例1:根据温度系数区间设定输出描述 temperature = 1.2 if temperature <= 0.3: description = "非常保守,几乎总是选择最高概率的 token" elif temperature <= 0.7: description = "平衡,在确定性和创造性之间折中" elif temperature <= 1.2: description = "较有创造性,输出更多样" else: description = "高度随机,可能产生出乎意料的内容" print(f"当前温度 {temperature} -> {description}") # 例2:根据错误码处理 API 异常 error_code = 429 if error_code == 200: print("请求成功") elif error_code == 401: print("认证失败,请检查 API 密钥") elif error_code == 429: print("请求频率超限,请稍后重试") elif error_code == 500: print("服务器内部错误,建议重试") else: print(f"未知错误码:{error_code}") # 例3:根据用户消息意图选择不同的处理方式(极简版本) message = "帮我写一首诗" if "翻译" in message: print("调用翻译模型") elif "写诗" in message or "作诗" in message: print("使用创意写作模型") elif "解释" in message or "是什么" in message: print("使用知识库问答模型") else: print("使用通用对话模型")4.5 嵌套条件判断:条件里面还有条件
有时你需要在一个条件判断内部再做更细致的判断。这就是嵌套if。
4.5.1 基本语法
if 外部条件: if 内部条件: 内外都满足时执行 else: 外部满足但内部不满足 else: 外部不满足4.5.2 AI 场景实例
# 例1:检查模型调用是否成功,再检查返回结果是否有效 api_success = True response_text = "" if api_success: if response_text: print(f"回复内容:{response_text}") else: print("API 调用成功但返回内容为空") else: print("API 调用失败,请检查网络") # 例2:先判断模型是否支持流式输出,再判断用户是否请求流式 model_supports_stream = True user_wants_stream = True if model_supports_stream: if user_wants_stream: print("启用流式输出,逐词返回") else: print("模型支持流式,但用户选择不使用") else: print("当前模型不支持流式输出,将一次性返回完整结果")💡 嵌套层次不宜过深(超过 3 层),否则代码可读性变差。复杂的条件可以用
and/or简化。
4.6 条件表达式(三元运算符):一行简写
当你只需要根据条件给变量赋不同的值时,可以用更简洁的一行写法。
4.6.1 语法
变量 = 值1 if 条件 else 值2如果条件为真,取值1,否则取值2。
4.6.2 AI 场景实例
# 例1:设定温度默认值 user_temp = None temperature = user_temp if user_temp is not None else 0.7 # 上面等价于: temperature = 0.7 if user_temp is None else user_temp # 例2:根据是否超出限制决定截断标志 token_count = 5000 limit = 4096 need_truncate = True if token_count > limit else False # 当然也可以直接写 need_truncate = token_count > limit,这里仅演示语法 # 例3:选择回复风格 style = "creative" if temperature > 1.0 else "conservative" print(f"回复风格:{style}")4.7 for 循环:遍历数据集
循环让程序重复执行一段代码。for循环通常用于遍历一个序列(比如列表、字符串、范围),对每个元素执行相同的操作。
4.7.1 遍历列表(AI 中常用)
# 例1:依次处理多个提示词 prompts = ["介绍Python", "什么是AI", "写一首诗"] for prompt in prompts: print(f"正在处理:{prompt}") # 这里可以调用 API 并获取回复# 例2:批量检查模型是否在允许列表中 allowed_models = ["gpt-4", "gpt-3.5", "claude-3"] user_models = ["gpt-4", "llama-2", "claude-3"] for m in user_models: if m in allowed_models: print(f"✅ {m} 可用") else: print(f"❌ {m} 不可用")4.7.2 遍历字符串(处理提示词中的每个字符)
prompt = "你好AI" for ch in prompt: print(f"字符:{ch}")4.7.3 使用range()进行数字循环
range(n)生成从 0 到 n-1 的整数序列。常用于重复执行固定次数。
# 例1:重复调用模型 3 次,展示不同 temperature 的效果 for i in range(3): temp = 0.2 + i * 0.4 # 0.2, 0.6, 1.0 print(f"第 {i+1} 次,温度 = {temp}")# 例2:批量处理 token 块 total_tokens = 1500 batch_size = 500 for start in range(0, total_tokens, batch_size): end = min(start + batch_size, total_tokens) print(f"处理 token 区间 [{start}:{end}]")4.7.4for与enumerate():同时获取索引和值
当你既需要元素,又需要它的位置索引时使用。
messages = ["你好", "请介绍AI", "谢谢"] for idx, msg in enumerate(messages): print(f"第 {idx+1} 条消息:{msg}")4.8 while 循环:当条件满足时持续执行
while循环在条件为True时不断重复执行代码块,直到条件变为False。适用于直到某个状态改变才停止的场景。
4.8.1 基本语法
while 条件: 循环体⚠️ 一定要确保条件最终会变为False,否则会变成无限循环,程序卡死。
4.8.2 AI 场景实例
# 例1:模拟重试机制(API 调用失败时最多重试 3 次) retries = 0 success = False while retries < 3 and not success: print(f"第 {retries+1} 次尝试调用 API...") # 假设调用结果 if retries == 2: # 第三次成功 success = True else: print("调用失败,重试中...") retries += 1 if success: print("API 调用成功") else: print("重试次数用尽,请稍后重试")# 例2:等待用户输入有效的温度值 temp = None while temp is None: user_input = input("请输入温度系数(0~2):") if user_input == "": print("不能为空,请重新输入") continue try: val = float(user_input) if 0 <= val <= 2: temp = val else: print("请输入 0 到 2 之间的数字") except ValueError: print("请输入有效的数字") print(f"已设置温度:{temp}")# 例3:逐步减少剩余 token 直到用完 remaining_tokens = 1024 while remaining_tokens > 0: # 每次消耗 100~200 token chunk = min(200, remaining_tokens) print(f"发送 {chunk} 个 token") remaining_tokens -= chunk print(f"剩余 {remaining_tokens}") print("Token 已用完")4.9 循环控制:break,continue,else
4.9.1break:立即退出整个循环
常用于找到目标后提前结束。
# 例:检查提示词中是否包含敏感词,一旦发现立即停止 sensitive = ["暴力", "色情"] prompt = "请介绍一下暴力美学" found = False for word in sensitive: if word in prompt: print(f"检测到敏感词:{word}") found = True break # 不再检查剩余词 if not found: print("提示词通过安全检查")4.9.2continue:跳过本次循环剩余代码,进入下一次迭代
# 例:处理消息列表,忽略空消息 messages = ["你好", "", "请介绍AI", "", "谢谢"] for msg in messages: if msg == "": continue # 跳过空消息 print(f"处理消息:{msg}")4.9.3for-else和while-else
else块在循环正常结束(没有被break中断)后执行。如果循环被break退出,则跳过else。
# 例:检查模型是否在允许列表中 allowed = ["gpt-4", "claude-3"] model = "llama-2" for m in allowed: if model == m: print("模型可用") break else: print("模型不在允许列表中,拒绝请求") # 因为没有 break 才会执行4.10 综合实战:AI 对话请求处理器
将if、for、while等知识融合成一个能处理用户请求、校验参数、重试 API 调用的脚本。
import time # 模拟的模型 API 调用函数(这里只打印信息) def call_model(prompt, temperature, max_tokens): print(f"[调用模型] prompt={prompt[:20]}... temp={temperature}, max_tokens={max_tokens}") # 假设有时会失败,用随机数模拟 import random if random.random() < 0.2: # 20% 失败率 return None, "服务器繁忙" else: return "这是模拟的回复内容。", None # 用户请求配置 user_prompts = [ "请解释一下大语言模型的工作原理", "写一首关于人工智能的短诗", "介绍一下 Transformer 架构", ] # 全局参数 default_temperature = 0.7 max_retries = 2 # 处理每个提示词 for idx, prompt in enumerate(user_prompts, 1): print(f"\n--- 处理第 {idx} 个请求 ---") # 1. 参数校验(if-elif) if len(prompt) == 0: print("错误:提示词为空,跳过") continue elif len(prompt) > 8000: print("提示词过长,截断至 8000 字符") prompt = prompt[:8000] # 2. 温度设置(三元表达式) temperature = default_temperature if default_temperature is None else default_temperature # 3. 重试循环(while) retry_count = 0 success = False response = None error = None while retry_count <= max_retries and not success: print(f"尝试 {retry_count+1}/{max_retries+1}") response, error = call_model(prompt, temperature, max_tokens=1024) if response is not None: success = True break else: print(f"调用失败:{error}") retry_count += 1 if retry_count <= max_retries: wait = 2 ** retry_count # 指数退避 print(f"等待 {wait} 秒后重试...") time.sleep(wait) # 4. 最终结果处理(if-else) if success: print(f"✅ 回复:{response[:100]}...") # 可以继续检查回复中是否包含结束标志 if "[END]" in response: print("检测到结束标记,停止进一步处理") else: print(f"❌ 请求失败,已重试 {max_retries} 次") print("\n所有请求处理完毕")输出如下内容:
tianpeng@DESKTOP-4L1UF5S:~/my-ai-service$ poetry run python src/my_ai_service/loop.py --- 处理第 1 个请求 --- 尝试 1/3 [调用模型] prompt=请解释一下大语言模型的工作原理... temp=0.7, max_tokens=1024 ✅ 回复:这是模拟的回复内容。... --- 处理第 2 个请求 --- 尝试 1/3 [调用模型] prompt=写一首关于人工智能的短诗... temp=0.7, max_tokens=1024 ✅ 回复:这是模拟的回复内容。... --- 处理第 3 个请求 --- 尝试 1/3 [调用模型] prompt=介绍一下 Transformer 架构... temp=0.7, max_tokens=1024 调用失败:服务器繁忙 等待 2 秒后重试... 尝试 2/3 [调用模型] prompt=介绍一下 Transformer 架构... temp=0.7, max_tokens=1024 ✅ 回复:这是模拟的回复内容。... 所有请求处理完毕4.11 本章小结
流程控制结构 | 作用 | AI 典型应用 |
|---|---|---|
| 条件成立时执行 | 参数合法性检查 |
| 二选一 | 模型是否支持某功能 |
| 多分支选择 | 根据错误码分类处理、根据温度区间确定风格 |
嵌套 | 多重条件细化 | 先判断调用成功,再判断返回内容 |
三元运算符 | 简洁的条件赋值 | 默认值设置 |
| 遍历序列 | 批量处理 prompt、检查敏感词列表 |
| 条件满足时重复 | API 重试机制、等待用户有效输入 |
| 提前结束循环 | 找到敏感词后停止 |
| 跳过本次迭代 | 忽略空消息 |
| 循环未被打断时执行 | 检查没有匹配项后执行默认动作 |