学AI,懂这些Python就够了(一):变量·数据类型·控制流·函数·类 —— 30分钟搞定Python核心语法
系列:「学AI,懂这些Python就够了」—— 面向AI智能体开发者的Python速成指南
标签:
PythonAI Agent编程基础入门教程难度:⭐⭐☆☆☆
前言
如果你想进入AI智能体(AI Agent)开发领域,Python是绕不开的第一道门槛。无论你是调用GPT接口、搭建LangChain应用,还是构建多智能体协作系统,都需要扎实的Python功底。
但问题是——你不需要学完一本800页的Python教程才能开始做AI。对于AI应用层开发者来说,真正高频使用的Python知识只占全部语法的30%。这篇文章就帮你把这30%挑出来,用最短的时间建立起能干活的能力。
本文是 「学AI,懂这些Python就够了」 系列的第一篇,带你快速掌握Python五大核心基础:变量、数据类型、控制流、函数、类。
1. 变量:Python世界的乐高积木
1.1 Python是动态类型语言
与Java、C++不同,Python 不需要声明变量类型,解释器会自动推断:
# 直接赋值即可,无需声明类型
name = "AI Agent" # 字符串
count = 10 # 整数
price = 3.14 # 浮点数
active = True # 布尔值
nothing = None # 空值
1.2 多重赋值与交换
Python 有一些让人眼前一亮的语法糖:
# 同时给多个变量赋值
x, y, z = 1, 2, 3
# 一行代码交换两个变量的值(不需要临时变量!)
a, b = 10, 20
a, b = b, a # a=20, b=10
# 链式赋值
width = height = depth = 100
1.3 命名规范
Python社区遵循 PEP 8 命名约定:
# ✅ 推荐:snake_case
user_name = "张三"
max_retry_count = 3
api_base_url = "https://api.openai.com"
# ❌ 不推荐:camelCase(这是JavaScript风格)
userName = "张三"
# 常量:全大写 + 下划线
OPENAI_API_KEY = "sk-xxxx"
MAX_TOKENS = 4096
DEFAULT_MODEL = "gpt-4"
1.4 动态类型与类型查看
# 变量可以随时改变类型
x = 42
print(type(x)) # <class 'int'>
x = "hello"
print(type(x)) # <class 'str'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>
💡 AI开发中的应用:在调用LLM API时,响应数据的类型可能是动态变化的,
type()函数可以帮助你快速调试。
2. 数据类型:你的数据住在什么房子里
Python有 8种核心数据类型,但对于AI开发,以下5种你每天都会用到:
2.1 列表(List)—— 可变有序序列
# 创建列表
messages = [
{"role": "system", "content": "你是一个AI助手"},
{"role": "user", "content": "介绍一下Python"},
]
# 增删改查
messages.append({"role": "assistant", "content": "Python是..."}) # 追加
first_msg = messages[0] # 索引访问
sliced = messages[1:3] # 切片
messages[-1] # 倒数第一个元素
# 列表推导式 —— AI开发者的最爱
squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# 实际场景:批量处理API响应
results = [process_response(r) for r in api_responses]
2.2 字典(Dict)—— 键值对映射
# 创建字典
config = {
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 2048,
"messages": [{"role": "user", "content": "Hello"}],
}
# 常用操作
model = config["model"] # 取值(KeyError if missing)
model = config.get("model", "gpt-3.5-turbo") # 安全取值,带默认值
config["stream"] = True # 添加/修改
config.update({"top_p": 0.9}) # 批量更新
# 遍历
for key, value in config.items():
print(f"{key}: {value}")
# 字典推导式
squared = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
💡 AI开发中的应用:LLM API的请求参数和响应结果几乎都是字典结构,熟练掌握字典操作是基本功。
2.3 元组(Tuple)—— 不可变有序序列
# 元组一旦创建就不能修改
point = (3, 4)
rgb = (255, 128, 0)
# 常用于函数返回多值
def get_model_config():
return ("gpt-4", 0.7, 4096)
model, temp, tokens = get_model_config() # 元组解包
2.4 集合(Set)—— 无序不重复元素
# 去重场景
tags = {"python", "ai", "agent", "python"} # 自动去重
# {'python', 'ai', 'agent'}
# 集合运算 —— 查找交集、并集、差集
my_skills = {"python", "langchain", "docker"}
job_requires = {"python", "aws", "docker"}
need_to_learn = job_requires - my_skills # {'aws'}
already_know = my_skills & job_requires # {'python', 'docker'}
2.5 字符串(Str)—— 自然语言处理的基石
# f-string 格式化 —— Python 3.6+ 最优雅的方式
name = "GPT-4"
temperature = 0.7
prompt = f"使用模型{name},温度={temperature}"
# 字符串常用方法
" hello ".strip() # "hello"
"a,b,c".split(",") # ['a', 'b', 'c']
"Hello World".lower() # "hello world"
"hello world".title() # "Hello World"
# 多行字符串 —— 写Prompt模板的神器
system_prompt = """你是一个专业的AI助手。
你的职责是:
1. 准确回答问题
2. 友好地与用户交流
3. 遇到不确定的内容主动说明"""
2.6 数据类型对比速查表
| 类型 | 可变 | 有序 | 允许重复 | 创建示例 | AI开发场景 |
|---|---|---|---|---|---|
list |
✅ | ✅ | ✅ | [1, 2, 3] |
消息列表、批量结果 |
tuple |
❌ | ✅ | ✅ | (1, 2, 3) |
配置常量、多返回值 |
dict |
✅ | ❌ | 键不可重复 | {"a": 1} |
API参数、响应数据 |
set |
✅ | ❌ | ❌ | {1, 2, 3} |
标签去重、集合运算 |
str |
❌ | ✅ | ✅ | "hello" |
Prompt模板、文本处理 |
2.7 类型检查与转换
# 类型检查
isinstance(42, int) # True
isinstance("hello", str) # True
isinstance([1,2], list) # True
# 类型转换
int("42") # 42
str(3.14) # "3.14"
list("abc") # ['a', 'b', 'c']
dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}
3. 控制流:让程序学会做选择
3.1 条件判断
# if / elif / else —— 最基础的分支结构
response_status = 200
if response_status == 200:
print("请求成功!")
elif response_status == 429:
print("请求频率过高,需要限流!")
elif response_status >= 500:
print("服务器错误,需要重试")
else:
print(f"未知状态码:{response_status}")
# AI开发实战:处理API错误
def handle_api_error(status_code: int) -> str:
if status_code == 401:
return "API Key无效,请检查认证信息"
elif status_code == 429:
return "请求频率超限,请降低并发或升级套餐"
elif status_code >= 500:
return "服务器繁忙,建议重试"
else:
return f"请求失败,状态码:{status_code}"
3.2 三元表达式
# 一行搞定简单的if-else
model = "gpt-4" if task_complexity > 5 else "gpt-3.5-turbo"
# 等价于:
if task_complexity > 5:
model = "gpt-4"
else:
model = "gpt-3.5-turbo"
3.3 for 循环 —— AI开发者最常用的循环
# 遍历列表
for message in chat_history:
print(message["content"])
# 使用 range
for i in range(3): # 0, 1, 2
print(f"第{i+1}次尝试")
# enumerate —— 需要同时获取索引和值
for index, msg in enumerate(chat_history):
print(f"[{index}] {msg['role']}: {msg['content']}")
# zip —— 并行遍历多个列表
models = ["gpt-4", "claude-3", "gemini-pro"]
prices = [0.03, 0.015, 0.01]
for model, price in zip(models, prices):
print(f"{model}: ${price}/1K tokens")
3.4 while 循环 —— 重试与轮询场景
# 指数退避重试 —— AI API调用的标准做法
import time
max_retries = 5
retry_count = 0
base_delay = 1 # 初始等待1秒
while retry_count < max_retries:
response = call_llm_api(prompt)
if response.status_code == 200:
break
elif response.status_code == 429:
delay = base_delay * (2 ** retry_count) # 指数退避
print(f"限流,{delay}秒后重试...")
time.sleep(delay)
retry_count += 1
else:
raise Exception(f"API调用失败:{response.status_code}")
3.5 break 与 continue
# break —— 跳出循环
for item in items:
result = process(item)
if result.is_emergency: # 紧急情况立即停止
break
# continue —— 跳过当前迭代
for chunk in stream:
if not chunk.content: # 跳过空块
continue
yield chunk.content
3.6 列表推导式 —— Pythonic way
# 传统方式
results = []
for item in items:
if item["score"] > 0.8:
results.append(item["name"])
# 列表推导式 —— 一行搞定
results = [item["name"] for item in items if item["score"] > 0.8]
# 复杂场景也没问题
high_score_actions = [
tool["name"]
for tool in available_tools
if tool["confidence"] > 0.7 and tool["enabled"]
]
3.7 match 语句(Python 3.10+)
# 比多个if-elif更优雅的模式匹配
def handle_tool_call(tool_name: str):
match tool_name:
case "search":
return execute_search()
case "calculate":
return execute_calculation()
case "read_file" | "write_file": # 多个值匹配
return execute_file_operation()
case _: # 默认情况
return f"未知工具: {tool_name}"
4. 函数:封装你的代码工具箱
4.1 函数基础
def call_llm(prompt: str, model: str = "gpt-4") -> str:
"""调用LLM API并返回响应文本
Args:
prompt: 用户输入的提示词
model: 模型名称,默认为gpt-4
Returns:
模型生成的响应文本
"""
# 函数体
response = api.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
4.2 参数传递的灵活方式
# 位置参数 —— 按顺序传递
def create_message(role, content):
return {"role": role, "content": content}
msg = create_message("user", "Hello")
# 关键字参数 —— 按名称传递,顺序无关
msg = create_message(content="Hello", role="user")
# 默认参数 —— 不传则用默认值
def chat(prompt, model="gpt-4", temperature=0.7):
pass
# *args —— 接收任意数量的位置参数
def log_messages(*messages):
for msg in messages:
print(msg)
log_messages("msg1", "msg2", "msg3")
# **kwargs —— 接收任意数量的关键字参数
def build_request(**kwargs):
defaults = {"model": "gpt-4", "temperature": 0.7}
return {**defaults, **kwargs}
req = build_request(model="gpt-3.5-turbo", max_tokens=1024)
4.3 Lambda 函数 —— 匿名函数的妙用
# 一行函数,常用于排序和过滤
add = lambda x, y: x + y
# 实际场景:按置信度排序工具调用
tools = [{"name": "search", "confidence": 0.9},
{"name": "calc", "confidence": 0.5}]
tools.sort(key=lambda t: t["confidence"], reverse=True)
# 与 map/filter 配合
scores = [0.8, 0.3, 0.9, 0.5]
high_scores = list(filter(lambda s: s > 0.7, scores)) # [0.8, 0.9]
4.4 高阶函数 —— 函数是一等公民
# 函数作为参数传递
def with_retry(func, max_retries=3):
"""给任意函数添加重试机制"""
def wrapper(*args, **kwargs):
for i in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_retries - 1:
raise
print(f"第{i+1}次重试...")
return wrapper
# 使用
safe_api_call = with_retry(call_llm_api, max_retries=3)
result = safe_api_call("写一首诗")
4.5 装饰器 —— AI项目中无处不在
import time
from functools import wraps
# 计时装饰器 —— 监控每个工具调用的耗时
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f"[计时] {func.__name__} 耗时 {elapsed:.2f}秒")
return result
return wrapper
@timer
def search_knowledge_base(query: str):
"""搜索知识库"""
time.sleep(0.5) # 模拟搜索
return ["结果1", "结果2"]
# 另一个常用装饰器:缓存工具调用结果
def cache_result(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
4.6 生成器 —— 流式输出的秘密武器
# yield 关键字实现生成器
def stream_response(text: str):
"""模拟LLM流式输出,逐字返回"""
for char in text:
yield char
# 实际使用
for chunk in stream_response("你好,我是AI助手"):
print(chunk, end="", flush=True)
# 另一个实际场景:分批处理大量数据
def batch_process(items: list, batch_size: int = 10):
"""将大列表切分为小批次"""
for i in range(0, len(items), batch_size):
yield items[i:i + batch_size]
# 使用
for batch in batch_process(all_documents, batch_size=5):
embeddings = get_embeddings(batch)
store_in_vector_db(embeddings)
4.7 类型提示 —— 3.1.2节的重点
from typing import List, Dict, Optional, Union
# 有了类型提示,IDE可以更好地帮你补全
def process_messages(
messages: List[Dict[str, str]],
model: str = "gpt-4",
temperature: Optional[float] = None,
) -> str:
"""处理对话消息并返回响应"""
...
# Union 类型
def get_value(key: str) -> Union[str, int, None]:
...
# 结合 dataclasses 使用效果最佳
5. 类与面向对象:构建智能体的骨架
5.1 基本类定义
class SimpleAgent:
"""最简单的AI智能体类"""
# 类属性 —— 所有实例共享
default_model = "gpt-4"
def __init__(self, name: str, system_prompt: str):
# 实例属性 —— 每个实例独立
self.name = name
self.system_prompt = system_prompt
self.history = []
def chat(self, user_input: str) -> str:
"""与智能体对话"""
self.history.append({"role": "user", "content": user_input})
response = self._call_llm()
self.history.append({"role": "assistant", "content": response})
return response
def _call_llm(self) -> str:
"""内部方法:调用LLM(前缀_表示私有)"""
messages = [{"role": "system", "content": self.system_prompt}]
messages.extend(self.history[-10:]) # 只保留最近10轮
return call_api(messages)
5.2 实例方法 / 类方法 / 静态方法
class ToolRegistry:
tools = {} # 类属性,所有实例共享
def register(self, name: str, func): # 实例方法
"""注册工具"""
self.tools[name] = func
@classmethod
def get_tool(cls, name: str): # 类方法 — 第一个参数是类本身
"""通过类名调用获取工具"""
return cls.tools.get(name)
@staticmethod
def validate_tool_name(name: str) -> bool: # 静态方法 — 无需self/cls
"""验证工具名称合法性"""
return name.isidentifier()
5.3 继承 —— 构建智能体家族
class BaseAgent:
"""智能体基类"""
def __init__(self, name: str):
self.name = name
self.history = []
def respond(self, input_text: str) -> str:
raise NotImplementedError("子类必须实现此方法")
class ChatAgent(BaseAgent):
"""对话智能体 —— 继承BaseAgent"""
def __init__(self, name: str, personality: str):
super().__init__(name) # 调用父类构造函数
self.personality = personality
def respond(self, input_text: str) -> str:
prompt = f"你是一个{self.personality}的助手:{input_text}"
return call_llm(prompt)
class ToolAgent(BaseAgent):
"""工具调用智能体 —— 继承BaseAgent"""
def __init__(self, name: str, tools: list):
super().__init__(name)
self.tools = tools
def respond(self, input_text: str) -> str:
# 先判断是否需要调用工具
tool = self._select_tool(input_text)
if tool:
result = tool.execute()
return f"工具执行结果:{result}"
return call_llm(input_text)
5.4 @property —— 属性的高级控制
class APIClient:
def __init__(self, api_key: str):
self._api_key = api_key
self._request_count = 0
@property
def masked_key(self) -> str:
"""只读属性:返回脱敏后的API Key"""
return self._api_key[:6] + "****" + self._api_key[-4:]
@property
def request_count(self) -> int:
"""只读属性:请求计数"""
return self._request_count
@property
def is_rate_limited(self) -> bool:
"""动态计算的属性"""
return self._request_count > 100
5.5 魔术方法 —— 让类更Pythonic
class Message:
def __init__(self, role: str, content: str):
self.role = role
self.content = content
def __str__(self) -> str: # print()时调用
return f"[{self.role}] {self.content[:50]}..."
def __repr__(self) -> str: # 调试时的显示
return f"Message(role='{self.role}', content='{self.content[:20]}...')"
def __len__(self) -> int: # len()时调用
return len(self.content)
def __eq__(self, other) -> bool: # == 比较
return self.role == other.role and self.content == other.content
# 使用
msg = Message("user", "你好,请帮我写一首诗")
print(msg) # [user] 你好,请帮我写一首诗
print(len(msg)) # 11
5.6 上下文管理器 —— 资源管理的标准做法
class DatabaseConnection:
"""实现上下文管理器,确保连接正确关闭"""
def __init__(self, db_url: str):
self.db_url = db_url
def __enter__(self):
print(f"连接到 {self.db_url}")
self.connection = connect(self.db_url)
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
print("关闭连接")
self.connection.close()
return False # 不抑制异常
# 使用 with 语句
with DatabaseConnection("postgresql://...") as conn:
result = conn.query("SELECT * FROM users")
# 退出 with 块时自动关闭连接
5.7 @dataclass —— Python 3.7+ 的数据容器利器
from dataclasses import dataclass, field
from typing import List
@dataclass
class AgentConfig:
"""智能体配置的数据类"""
name: str
model: str = "gpt-4"
temperature: float = 0.7
max_tokens: int = 2048
tools: List[str] = field(default_factory=list)
system_prompt: str = ""
def to_api_params(self) -> dict:
"""转换为API调用参数"""
return {
"model": self.model,
"temperature": self.temperature,
"max_tokens": self.max_tokens,
}
# 使用非常简洁
config = AgentConfig(name="客服助手", temperature=0.3)
print(config.to_api_params())
6. AI项目中用到最多的内置函数
| 函数 | 用途 | AI开发场景示例 |
|---|---|---|
print() |
输出调试信息 | print(f"Token用量: {usage}") |
len() |
获取长度 | len(chat_history) 检查对话轮数 |
type() |
查看类型 | type(response) 调试API返回 |
isinstance() |
类型检查 | isinstance(result, dict) 验证响应格式 |
enumerate() |
带索引遍历 | 给消息列表添加序号 |
zip() |
并行遍历 | 同时遍历模型名和价格 |
sorted() |
排序 | 按置信度排序工具调用结果 |
map() |
批量映射 | 对一批文本执行相同的处理 |
filter() |
批量过滤 | 过滤低置信度的结果 |
sum() |
求和 | 计算总Token消耗 |
max() / min() |
最值 | 找最高/最低置信度 |
any() / all() |
全量判断 | 检查是否所有工具都执行成功 |
7. 总结与下一步
本篇核心知识点回顾
Python基础语法
├── 变量:动态类型、snake_case命名、多重赋值
├── 数据类型:list/dict/tuple/set/str 五大核心类型
├── 控制流:if/for/while + 列表推导式
├── 函数:参数传递、lambda、装饰器、生成器、类型提示
└── 类:继承、魔术方法、上下文管理器、dataclass
快速自测
- 能熟练使用列表推导式替代for循环
- 能写出带默认参数和类型提示的函数
- 会用
@property和@dataclass - 理解
__init__、__str__等魔术方法 - 能用
with语句管理资源
下一步
掌握了这些Python基础语法,你已经具备了编写AI智能体代码的基本能力。在下一篇文章中,我们将学习 Python异步编程——这是让AI智能体"快起来"的关键技术。
下一篇: 学AI,懂这些Python就够了(二):async/await 异步编程 —— 让AI智能体快10倍的并发秘籍
本文是「学AI,懂这些Python就够了」系列的第1篇,该系列面向AI应用层开发者,聚焦高频使用的Python知识,帮你用最短时间建立起能干活的能力。
更多推荐
所有评论(0)