第一篇章:Python 基础速通——从零到能写脚本
覆盖内容:环境搭建 → 数据类型 → 条件循环 → 列表字典 → 函数 → 文件读写 → 异常处理 → JSON → 实战
最终产出:一个命令行待办事项 Todo List
阅读耗时:约 60 分钟,跟练约 3-4 小时
一、为什么要学 Python?一句话就够了
大模型生态 99% 的工具链都是 Python。LangChain、LangGraph、FastAPI、ChromaDB、Dify——全部 Python。你用 Java 写后端,Python 写 AI 层,各做各最擅长的事。
本篇不追求精通,够用就行。学完你能读懂 AI 应用的代码,能写简单脚本。
二、环境搭建
2.1 安装 Python 3.12
Windows:去 https://www.python.org/downloads/ 下载 → 安装时 ⚠️ 勾选 “Add Python to PATH” → Install Now
macOS:
brew install python@3.12
Linux:
sudo apt install python3.12 python3.12-venv python3-pip -y
验证:
python --version # Windows
python3 --version # macOS / Linux
# 输出:Python 3.12.x
2.2 装 VSCode + Python 插件
去 https://code.visualstudio.com/ 下载安装。打开后在扩展商店搜索安装 Python。
2.3 创建项目 + 虚拟环境
mkdir ~/ai-learning
cd ~/ai-learning
# 创建虚拟环境
python -m venv venv # Windows
python3 -m venv venv # macOS / Linux
# 激活
venv\Scripts\activate # Windows CMD
source venv/bin/activate # macOS / Linux
激活成功标志:终端前面出现 (venv)。每次打开项目都要先激活。
2.4 第一个程序
新建 hello.py:
print("Hello AI! 你好,人工智能!")
运行:
python hello.py
三、变量与数据类型(基础中的基础)
3.1 四种核心类型
# 整数 int
age = 22
count = 100
# 浮点数 float
price = 19.99
pi = 3.1415926
# 字符串 str
name = "易秋扬"
message = '你好,世界'
# 布尔值 bool
is_student = True
has_job = False
3.2 变量命名规则
# ✅ 正确
user_name = "tom" # 下划线命名(Python 推荐)
userName = "tom" # 驼峰也行
_count = 1 # 下划线开头表示私有
# ❌ 错误
# 1st_place = "gold" # 不能数字开头
# user-name = "tom" # 不能用连字符
# class = "AI" # 不能和关键字重名
3.3 类型转换
age_str = "22"
age_int = int(age_str) # "22" → 22
score = 95
score_str = str(score) # 95 → "95"
pi = 3.14
pi_int = int(pi) # 3.14 → 3(直接截断,不是四舍五入)
3.4 字符串操作
# f-string:最常用的格式化方式
name = "小明"
age = 22
print(f"我叫{name},今年{age}岁")
# 常用方法
text = " Hello Python "
print(text.strip()) # "Hello Python"(去首尾空格)
print(text.upper()) # " HELLO PYTHON "
print(text.lower()) # " hello python "
print(text.replace("Python", "AI")) # " Hello AI "
动手:个人信息卡片
# card.py
name = input("请输入你的名字:")
age = int(input("请输入你的年龄:"))
city = input("请输入你的城市:")
print("\n" + "=" * 30)
print(f"姓名:{name}")
print(f"年龄:{age}")
print(f"城市:{city}")
print(f"十年后你 {age + 10} 岁")
print("=" * 30)
运行试试:
python card.py
四、条件判断与循环
4.1 if / elif / else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"成绩 {score},等级 {grade}")
4.2 比较运算符
a == b # 等于
a != b # 不等于
a > b # 大于
a >= b # 大于等于
a < b # 小于
a <= b # 小于等于
# 组合条件
if age >= 18 and age <= 60:
print("成年人")
if score < 0 or score > 100:
print("分数不合法")
if not is_student:
print("不是学生")
4.3 for 循环
# 遍历列表
fruits = ["苹果", "香蕉", "橘子", "葡萄"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# range:生成数字序列
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 11): # 1 到 10
print(i)
for i in range(0, 100, 10): # 0, 10, 20, ..., 90(步长 10)
print(i)
# enumerate:同时拿索引和值
for index, fruit in enumerate(fruits, 1):
print(f"{index}. {fruit}")
4.4 while 循环
# 倒计时
count = 5
while count > 0:
print(count)
count -= 1
print("发射!")
# ⚠️ 别忘了退出条件,否则死循环
动手:猜数字游戏
# guess_number.py
import random
target = random.randint(1, 100)
guess = 0
attempts = 0
print("猜数字游戏!1-100 之间")
while guess != target:
guess = int(input("你猜是多少? "))
attempts += 1
if guess > target:
print("太大了!")
elif guess < target:
print("太小了!")
else:
print(f"恭喜!答案就是 {target},你猜了 {attempts} 次")
五、列表与字典(数据处理核心)
5.1 列表 list
# 创建
fruits = ["苹果", "香蕉", "橘子"]
mixed = [1, "hello", 3.14, True] # 可以混类型
empty = [] # 空列表
# 访问(索引从 0 开始)
print(fruits[0]) # "苹果"
print(fruits[-1]) # "橘子"(倒数第一个)
print(fruits[0:2]) # ["苹果", "香蕉"](切片)
# 增
fruits.append("葡萄") # 末尾加
fruits.insert(1, "草莓") # 指定位置插入
# 删
fruits.remove("香蕉") # 按值删除
popped = fruits.pop() # 删最后一个,返回它
popped = fruits.pop(0) # 删指定位置
# 改
fruits[0] = "青苹果"
# 查
print(len(fruits)) # 长度
print("苹果" in fruits) # 是否存在,返回 True/False
print(fruits.index("橘子")) # 找位置
5.2 字典 dict
# 创建
student = {
"name": "小明",
"age": 22,
"scores": [85, 90, 78],
"is_graduated": False
}
# 访问
print(student["name"]) # "小明"
print(student.get("phone", "无")) # 不存在返回默认值,不报错
# 增/改
student["phone"] = "13800138000" # 新增
student["age"] = 23 # 修改
# 删
del student["is_graduated"]
phone = student.pop("phone")
# 遍历
for key, value in student.items():
print(f"{key}: {value}")
5.3 列表推导式(Pythonic 写法)
# 普通写法
squares = []
for i in range(10):
squares.append(i ** 2)
# 推导式(一行搞定)
squares = [i ** 2 for i in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 加条件
evens = [i for i in range(20) if i % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
动手:学生成绩管理系统
# grade_system.py
students = []
while True:
print("\n=== 学生成绩管理系统 ===")
print("1. 添加学生")
print("2. 查看所有学生")
print("3. 查找学生")
print("4. 退出")
choice = input("请选择:")
if choice == "1":
name = input("姓名:")
score = int(input("分数:"))
students.append({"name": name, "score": score})
print(f"已添加 {name}")
elif choice == "2":
if not students:
print("还没有学生记录")
else:
avg = sum(s["score"] for s in students) / len(students)
for s in students:
print(f" {s['name']}: {s['score']} 分")
print(f" 平均分: {avg:.1f}")
elif choice == "3":
name = input("输入要查找的姓名:")
found = [s for s in students if s["name"] == name]
if found:
print(f" {found[0]['name']}: {found[0]['score']} 分")
else:
print(f" 未找到 {name}")
elif choice == "4":
print("再见!")
break
else:
print("无效选择,重新输入")
六、函数(代码复用)
6.1 定义与调用
def greet(name):
"""向某人打招呼""" # 这叫 docstring,写函数说明
return f"你好,{name}!"
print(greet("小明")) # "你好,小明!"
# 多个参数
def add(a, b):
return a + b
print(add(3, 5)) # 8
6.2 默认参数
def greet(name, greeting="你好"):
return f"{greeting},{name}!"
print(greet("小明")) # "你好,小明!"
print(greet("Tom", greeting="Hello")) # "Hello,Tom!"
6.3 返回多个值
def get_user_info():
name = "小明"
age = 22
city = "武汉"
return name, age, city # 实际上是返回一个元组
n, a, c = get_user_info() # 解包
print(n, a, c)
动手:把成绩管理系统拆成函数
# grade_system_v2.py
def add_student(students, name, score):
students.append({"name": name, "score": score})
def show_all(students):
if not students:
print("还没有学生记录")
return
avg = sum(s["score"] for s in students) / len(students)
for s in students:
print(f" {s['name']}: {s['score']} 分")
print(f" 平均分: {avg:.1f}")
def find_student(students, name):
found = [s for s in students if s["name"] == name]
return found[0] if found else None
# 使用
students = []
add_student(students, "小明", 85)
add_student(students, "小红", 92)
show_all(students)
result = find_student(students, "小明")
if result:
print(f"找到:{result['name']}: {result['score']} 分")
七、文件读写
7.1 写文件
# 写文本
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
f.write("你好,世界!\n")
# w 模式:覆盖写入
# a 模式:追加写入
# encoding="utf-8":避免中文乱码,必须加
7.2 读文件
# 读全部
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # strip() 去掉末尾换行符
动手:日记本
# diary.py
from datetime import datetime
while True:
print("\n=== 日记本 ===")
print("1. 写日记")
print("2. 读日记")
print("3. 退出")
choice = input("请选择:")
if choice == "1":
content = input("今天想写什么?\n")
# 追加模式写入
with open("diary.txt", "a", encoding="utf-8") as f:
now = datetime.now().strftime("%Y-%m-%d %H:%M")
f.write(f"\n[{now}]\n{content}\n")
f.write("-" * 30)
print("已保存!")
elif choice == "2":
try:
with open("diary.txt", "r", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("还没有日记记录")
elif choice == "3":
break
八、异常处理
# 基础结构
try:
num = int(input("输入一个数字:"))
result = 100 / num
print(f"100 / {num} = {result}")
except ValueError:
print("这不是一个数字!")
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"未知错误:{e}")
finally:
print("不管有没有出错,我都会执行")
给日记本加上异常处理:
def read_diary():
try:
with open("diary.txt", "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
return "还没有日记记录"
except PermissionError:
return "没有权限读取文件"
九、JSON 数据处理
大模型 API 的请求和返回全是 JSON,必须会。
import json
# Python 对象 → JSON 字符串(序列化)
data = {
"name": "小明",
"age": 22,
"hobbies": ["编程", "篮球"],
"contact": {"phone": "13800000000", "email": "test@example.com"}
}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 输出:
# {
# "name": "小明",
# "age": 22,
# "hobbies": ["编程", "篮球"],
# "contact": {"phone": "13800000000", "email": "test@example.com"}
# }
# JSON 字符串 → Python 对象(反序列化)
parsed = json.loads(json_str)
print(parsed["name"]) # "小明"
print(parsed["hobbies"]) # ["编程", "篮球"]
# 读写 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
十、阶段实战:命令行 Todo List
综合运用本篇所有知识,写出一个完整的待办事项工具。
# todo.py —— 第一阶段毕业作品
import json
import os
from datetime import datetime
TODO_FILE = "todos.json"
def load_todos():
"""从 JSON 文件加载待办列表"""
if os.path.exists(TODO_FILE):
try:
with open(TODO_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_todos(todos):
"""保存待办列表到 JSON 文件"""
with open(TODO_FILE, "w", encoding="utf-8") as f:
json.dump(todos, f, ensure_ascii=False, indent=2)
def add_todo(todos):
"""添加新待办"""
title = input("待办事项:")
if not title.strip():
print("待办不能为空!")
return
todo = {
"id": len(todos) + 1,
"title": title.strip(),
"done": False,
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M")
}
todos.append(todo)
save_todos(todos)
print(f"✅ 已添加:{title}")
def list_todos(todos):
"""列出所有待办"""
if not todos:
print("📭 当前没有待办事项")
return
pending = [t for t in todos if not t["done"]]
done = [t for t in todos if t["done"]]
print(f"\n📋 待办事项(共 {len(todos)} 项,{len(pending)} 项未完成)")
print("-" * 50)
for t in todos:
status = "✅" if t["done"] else "⬜"
print(f" {status} [{t['id']}] {t['title']}")
print(f" 创建于 {t['created_at']}")
def toggle_todo(todos):
"""切换待办状态"""
try:
tid = int(input("输入待办编号:"))
for t in todos:
if t["id"] == tid:
t["done"] = not t["done"]
status = "完成" if t["done"] else "未完成"
save_todos(todos)
print(f"✅ [{tid}] {t['title']} → {status}")
return
print(f"❌ 找不到编号 {tid}")
except ValueError:
print("请输入有效数字")
def delete_todo(todos):
"""删除待办"""
try:
tid = int(input("输入要删除的待办编号:"))
for i, t in enumerate(todos):
if t["id"] == tid:
removed = todos.pop(i)
save_todos(todos)
print(f"🗑️ 已删除:{removed['title']}")
return
print(f"❌ 找不到编号 {tid}")
except ValueError:
print("请输入有效数字")
def main():
"""主程序"""
todos = load_todos()
print("=" * 50)
print(" 📝 Todo List · 第一阶段毕业作品")
print("=" * 50)
while True:
print("\n1. 添加待办 2. 查看列表 3. 切换状态 4. 删除 5. 退出")
choice = input("请选择:").strip()
if choice == "1":
add_todo(todos)
elif choice == "2":
list_todos(todos)
elif choice == "3":
toggle_todo(todos)
elif choice == "4":
delete_todo(todos)
elif choice == "5":
print("👋 再见!你的数据已保存在 todos.json")
break
else:
print("无效选择,请输入 1-5")
if __name__ == "__main__":
main()
运行试试
python todo.py
本篇总结
知识点 你学会了什么
────────────────────────────────────────
环境搭建 Python + VSCode + venv,职业生涯的起点
变量与数据类型 int / float / str / bool,数据的基本单位
条件判断 if/elif/else,让程序做决策
循环 for / while,让程序重复做事
列表与字典 处理批量数据、结构化数据的核心容器
函数 def,把代码组织成可复用的模块
文件读写 open / with,数据持久化
异常处理 try/except,程序不崩溃
JSON json.dumps / loads,和大模型 API 交互的格式
实战 Todo List,第一个完整项目
下一篇预告
第二篇章:API 调用入门——注册 DeepSeek、拿到 API Key、发出人生第一行大模型请求。正式开始 AI 之旅。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)