# Python 零基础到实战 · 系统学习教程
---
## 一、学习路线图
```
第1阶段:基础语法(1-2周)
↓
第2阶段:数据结构(1-2周)
↓
第3阶段:函数与模块(1周)
↓
第4阶段:面向对象(1-2周)
↓
第5阶段:实用库入门(2-3周)
↓
第6阶段:项目实战(持续)
```
---
## 二、第1阶段:基础语法
### 2.1 变量与数据类型
```python
# 数字
age = 25 # 整数 int
price = 9.99 # 浮点数 float
complex_num = 3+4j # 复数 complex
# 字符串
name = "小H"
msg = '你好'
multi_line = """
多行字符串
用三引号
"""
# 布尔值
is_learning = True
is_boring = False
# 空值
nothing = None
# 类型查看与转换
type(age) # <class 'int'>
int("123") # 字符串转整数 → 123
str(123) # 整数转字符串 → "123"
float("3.14") # 字符串转浮点 → 3.14
```
### 2.2 运算符
```python
# 算术运算
10 + 3 # 13 加
10 - 3 # 7 减
10 * 3 # 30 乘
10 / 3 # 3.33 除(结果为float)
10 // 3 # 3 整除
10 % 3 # 1 取余
10 ** 3 # 1000 幂运算
# 比较运算
5 == 5 # True 等于
5 != 3 # True 不等于
5 > 3 # True 大于
5 < 3 # False 小于
5 >= 5 # True 大于等于
# 逻辑运算
True and False # False 与
True or False # True 或
not True # False 非
# 赋值运算
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4
```
### 2.3 字符串操作
```python
s = "Hello Python"
# 索引与切片
s[0] # 'H' 第一个字符
s[-1] # 'n' 最后一个字符
s[0:5] # 'Hello' 切片 [起:止)
s[:5] # 'Hello' 省略起点
s[6:] # 'Python' 省略终点
s[::2] # 'HloPto' 步长为2
s[::-1] # 'nohtyP olleH' 反转
# 常用方法
len(s) # 12 长度
s.lower() # 'hello python' 转小写
s.upper() # 'HELLO PYTHON' 转大写
s.strip() # 去除两端空白
s.replace("Python", "World") # 替换
s.split(" ") # ['Hello', 'Python'] 分割
"-".join(['a','b']) # 'a-b' 连接
"Python" in s # True 包含判断
s.count("o") # 1 计数
s.find("Python") # 6 查找位置
s.startswith("Hello") # True 前缀判断
# f-string 格式化(推荐)
name = "小H"
age = 25
print(f"我是{name},今年{age}岁")
print(f"计算结果:{2**10:,}") # 计算结果:1,024
print(f"保留2位:{3.14159:.2f}") # 保留2位:3.14
```
### 2.4 输入与输出
```python
# 输出
print("Hello World")
print("姓名", "年龄", sep=" | ") # 姓名 | 年龄
print("加载中...", end="") # 不换行
# 输入
name = input("请输入姓名:") # 返回字符串
age = int(input("请输入年龄:")) # 转为整数
```
---
## 三、第2阶段:数据结构
### 3.1 列表 List(最常用)
```python
# 创建
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14] # 可混合类型
nested = [[1,2], [3,4]] # 可嵌套
# 增
fruits.append("葡萄") # 末尾添加
fruits.insert(1, "西瓜") # 指定位置插入
fruits.extend(["芒果", "梨"]) # 扩展列表
# 删
fruits.remove("香蕉") # 按值删除
fruits.pop() # 删除末尾并返回
fruits.pop(0) # 删除指定位置
del fruits[0] # 按索引删除
# 改
fruits[0] = "草莓" # 修改元素
# 查
fruits[0] # 第一个
fruits[-1] # 最后一个
"苹果" in fruits # True
fruits.index("橙子") # 查找索引
fruits.count("苹果") # 计数
# 切片
fruits[1:3] # 第2到第3个
# 排序
fruits.sort() # 原地排序
fruits.sort(reverse=True) # 原地倒序
sorted(fruits) # 返回新排序列表
numbers.reverse() # 原地反转
# 列表推导式(Pythonic写法)
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 常用操作
len(fruits) # 长度
sum(numbers) # 求和
max(numbers) # 最大值
min(numbers) # 最小值
```
### 3.2 元组 Tuple(不可变)
```python
# 创建
point = (3, 4)
single = (1,) # 单元素元组必须加逗号
coordinates = 10, 20 # 省略括号也可
# 解包
x, y = point
print(f"x={x}, y={y}") # x=3, y=4
# 用途:固定数据、字典键、函数返回多值
def get_user():
return "小H", 25
name, age = get_user()
```
### 3.3 字典 Dict(键值对)
```python
# 创建
user = {
"name": "小H",
"age": 25,
"skills": ["Python", "网络技术"]
}
# 访问
user["name"] # '小H'
user.get("email", "未设置") # 未设置(不存在时返回默认值)
# 增/改
user["email"] = "xh@example.com" # 键存在则修改,不存在则添加
user.update({"city": "贵州", "age": 26}) # 批量更新
# 删
del user["email"]
user.pop("city") # 删除并返回值
# 遍历
for key in user: # 遍历键
print(key)
for key, value in user.items(): # 遍历键值对
print(f"{key}: {value}")
for value in user.values(): # 遍历值
print(value)
# 常用操作
"user" in user # False(键不存在)
len(user) # 键值对数量
list(user.keys()) # 所有键
list(user.values()) # 所有值
# 字典推导式
scores = {"语文": 90, "数学": 95, "英语": 88}
high = {k: v for k, v in scores.items() if v >= 90}
# {'语文': 90, '数学': 95}
# 嵌套字典
students = {
"001": {"name": "小H", "score": 95},
"002": {"name": "小李", "score": 88}
}
```
### 3.4 集合 Set(去重 + 集合运算)
```python
# 创建
colors = {"红", "绿", "蓝"}
nums = set([1, 2, 2, 3, 3]) # {1, 2, 3} 自动去重
# 操作
colors.add("黄") # 添加
colors.remove("红") # 删除(不存在会报错)
colors.discard("紫") # 删除(不存在不报错)
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # {1,2,3,4,5,6} 并集
a & b # {3,4} 交集
a - b # {1,2} 差集
a ^ b # {1,2,5,6} 对称差集
# 实用:列表去重
dup_list = [1, 2, 2, 3, 3, 4]
unique = list(set(dup_list)) # [1, 2, 3, 4]
```
---
## 四、第3阶段:流程控制
### 4.1 条件判断
```python
# if-elif-else
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
# 三元表达式
result = "通过" if score >= 60 else "不通过"
# match-case(Python 3.10+)
command = "start"
match command:
case "start":
print("启动")
case "stop":
print("停止")
case _:
print("未知命令")
```
### 4.2 循环
```python
# for 循环
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 10, 2): # 1,3,5,7,9
print(i)
fruits = ["苹果", "香蕉", "橙子"]
for index, fruit in enumerate(fruits):
print(f"第{index+1}个:{fruit}")
# 同时遍历两个列表
names = ["小H", "小李"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name}: {age}岁")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# break 和 continue
for i in range(10):
if i == 3:
continue # 跳过3
if i == 8:
break # 到8就停
print(i) # 输出 0,1,2,4,5,6,7
# for-else(循环正常结束执行else)
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
break
else:
print(f"{n}是质数") # 2,3,5,7
```
---
## 五、第4阶段:函数与模块
### 5.1 函数定义
```python
# 基本函数
def greet(name):
return f"你好,{name}!"
msg = greet("小H")
# 默认参数
def connect(host, port=3306):
print(f"连接 {host}:{port}")
connect("localhost") # localhost:3306
connect("localhost", 3307) # localhost:3307
# 关键字参数
def user_info(name, age, city="未知"):
print(f"{name}, {age}岁, {city}")
user_info(name="小H", age=25, city="贵州")
# *args 和 **kwargs
def total(*args):
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4, 5) # 15
def profile(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
profile(name="小H", age=25)
# 返回多个值
def calc(a, b):
return a+b, a-b, a*b, a/b
add, sub, mul, div = calc(10, 3)
# Lambda 匿名函数
square = lambda x: x ** 2
square(5) # 25
# 常与排序配合
users = [{"name": "小李", "age": 30}, {"name": "小H", "age": 25}]
users.sort(key=lambda u: u["age"]) # 按age排序
# 类型提示(Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
```
### 5.2 模块与包
```python
# 导入模块
import os
import datetime
# 从模块导入指定内容
from datetime import datetime, timedelta
from os.path import exists, join
# 别名导入
import numpy as np
import pandas as pd
# 创建自己的模块
# 文件:my_utils.py
"""
def add(a, b):
return a + b
def is_even(n):
return n % 2 == 0
"""
# 使用
import my_utils
my_utils.add(1, 2)
# 常用内置模块速查
import os # 操作系统
import sys # 系统相关
import json # JSON处理
import re # 正则表达式
import datetime # 日期时间
import collections # 高级数据结构
import pathlib # 路径操作
import logging # 日志
import hashlib # 加密
import itertools # 迭代工具
```
---
## 六、第5阶段:面向对象
### 6.1 类与对象
```python
class Dog:
# 类属性(所有实例共享)
species = "犬科"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def bark(self):
return f"{self.name}:汪汪!"
def info(self):
return f"{self.name},{self.age}岁"
# 创建实例
dog1 = Dog("旺财", 3)
dog2 = Dog("来福", 5)
print(dog1.bark()) # 旺财:汪汪!
print(dog2.info()) # 来福,5岁
print(Dog.species) # 犬科
```
### 6.2 继承
```python
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name}在吃东西"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # 调用父类初始化
self.color = color
def meow(self):
return f"{self.name}:喵喵!"
cat = Cat("小橘", "橘色")
print(cat.eat()) # 小橘在吃东西(继承自Animal)
print(cat.meow()) # 小橘:喵喵!
```
### 6.3 魔术方法
```python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
v1 = Vector(3, 4)
v2 = Vector(1, 2)
v3 = v1 + v2 # Vector(4, 6)
print(v3) # Vector(4, 6)
```
---
## 七、第6阶段:实用库入门
### 7.1 文件操作
```python
# 读文件
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
# lines = f.readlines() # 按行读取为列表
# for line in f: # 逐行读取(省内存)
# 写文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
f.writelines(["行1\n", "行2\n"])
# CSV
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["姓名"], row["分数"])
# JSON
import json
data = {"name": "小H", "scores": [90, 95, 88]}
json_str = json.dumps(data, ensure_ascii=False, indent=2) # 转JSON字符串
parsed = json.loads(json_str) # 解析
with open("data.json", "w") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("data.json") as f:
loaded = json.load(f)
# pathlib(推荐替代os.path)
from pathlib import Path
p = Path("data")
p.mkdir(exist_ok=True) # 创建目录
list(p.glob("*.csv")) # 查找文件
p / "subdir" / "file.txt" # 路径拼接
```
### 7.2 正则表达式
```python
import re
# 查找
re.findall(r'\d+', "a1b22c333") # ['1', '22', '333']
re.search(r'(\d+)-(\d+)', "2026-04-28").groups() # ('2026', '04')
# 替换
re.sub(r'\d+', 'N', "a1b2c3") # 'aNbNcN'
# 分割
re.split(r'[,;]', "a,b;c") # ['a', 'b', 'c']
# 常用模式
phone = re.match(r'^1[3-9]\d{9}$', "13800138000") # 手机号
email = re.match(r'^[\w.]+@[\w]+\.[\w]+$', "a@b.com")
```
### 7.3 网络请求
```python
import urllib.request
import json
# urllib(内置,无需安装)
url = "https://api.example.com/data"
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode())
print(data)
# requests(第三方,推荐 pip install requests)
import requests
# GET
r = requests.get("https://httpbin.org/get", params={"key": "value"}, timeout=10)
r.json()
# POST
r = requests.post("https://httpbin.org/post", json={"name": "小H"})
# 下载文件
r = requests.get("https://example.com/file.zip", stream=True)
with open("file.zip", "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
```
### 7.4 日期时间
```python
from datetime import datetime, timedelta, timezone
now = datetime.now() # 当前时间
today = datetime.today() # 今天
utc_now = datetime.now(timezone.utc) # UTC时间
# 格式化
now.strftime("%Y-%m-%d %H:%M:%S") # '2026-04-28 10:36:00'
now.strftime("%Y年%m月%d日") # '2026年04月28日'
# 解析
dt = datetime.strptime("2026-04-28", "%Y-%m-%d")
# 计算
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
one_hour_later = now + timedelta(hours=1)
diff = tomorrow - now
diff.days # 1
diff.total_seconds() # 86400.0
```
---
## 八、第7阶段:项目实战
### 8.1 实战1:网络设备巡检脚本
```python
#!/usr/bin/env python3
"""交换机巡检脚本 - 批量检查设备状态"""
import json
import datetime
from pathlib import Path
# 设备清单
DEVICES = [
{"host": "192.168.1.1", "name": "核心交换机A"},
{"host": "192.168.1.2", "name": "核心交换机B"},
{"host": "192.168.2.1", "name": "接入交换机1"},
]
def check_device(device):
"""模拟设备巡检"""
result = {
"device": device["name"],
"host": device["host"],
"check_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"status": "正常",
"cpu": "15%",
"memory": "42%",
"interfaces": 24,
"alarm": []
}
# 实际场景中用 paramiko/netmiko SSH 登录设备执行命令
return result
def generate_report(results):
"""生成巡检报告"""
report = []
report.append("=" * 50)
report.append("网络设备巡检报告")
report.append(f"巡检时间:{results[0]['check_time']}")
report.append("=" * 50)
for r in results:
report.append(f"\n📋 {r['device']} ({r['host']})")
report.append(f" 状态:{r['status']}")
report.append(f" CPU:{r['cpu']} 内存:{r['memory']}")
report.append(f" 接口数:{r['interfaces']}")
if r["alarm"]:
report.append(f" ⚠️ 告警:{', '.join(r['alarm'])}")
else:
report.append(" ✅ 无告警")
return "\n".join(report)
# 主程序
if __name__ == "__main__":
results = [check_device(d) for d in DEVICES]
report = generate_report(results)
print(report)
# 保存为JSON
Path("inspection_reports").mkdir(exist_ok=True)
date_str = datetime.datetime.now().strftime("%Y%m%d")
with open(f"inspection_reports/report_{date_str}.json", "w") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\n✅ 报告已保存")
```
### 8.2 实战2:股票数据查询
```python
#!/usr/bin/env python3
"""A股行情查询脚本"""
import urllib.request
import json
import re
def get_stock_price(code):
"""通过新浪API获取股票实时行情"""
# 沪市前缀sh,深市前缀sz
prefix = "sh" if code.startswith("6") else "sz"
url = f"http://hq.sinajs.cn/list={prefix}{code}"
req = urllib.request.Request(url, headers={
"Referer": "https://finance.sina.com.cn",
"User-Agent": "Mozilla/5.0"
})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read().decode("gbk")
match = re.search(r'="([^"]+)"', raw)
if match:
fields = match.group(1).split(",")
return {
"名称": fields[0],
"今开": fields[1],
"昨收": fields[2],
"当前价": fields[3],
"最高": fields[4],
"最低": fields[5],
"成交量(手)": fields[8],
"成交额(万)": fields[9],
}
except Exception as e:
return {"error": str(e)}
# 使用
if __name__ == "__main__":
# 查盛视科技
data = get_stock_price("002990")
if "error" not in data:
print(f"📊 {data['名称']} 当前价:{data['当前价']}")
print(f" 今开:{data['今开']} 昨收:{data['昨收']}")
print(f" 最高:{data['最高']} 最低:{data['最低']}")
else:
print(f"查询失败:{data['error']}")
```
### 8.3 实战3:日志分析工具
```python
#!/usr/bin/env python3
"""分析交换机/服务器日志,提取关键告警"""
import re
from collections import Counter
def analyze_log(filepath, keywords=None):
"""分析日志文件"""
if keywords is None:
keywords = ["error", "warning", "failed", "down", "critical",
"错误", "警告", "故障", "宕机"]
alerts = []
pattern = re.compile("|".join(keywords), re.IGNORECASE)
with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
for line_num, line in enumerate(f, 1):
if pattern.search(line):
alerts.append({
"line": line_num,
"content": line.strip(),
"keyword": pattern.search(line).group().lower()
})
# 统计关键词出现频率
keyword_counts = Counter(a["keyword"] for a in alerts)
# 输出报告
print(f"📄 日志分析报告:{filepath}")
print(f" 总行数:{line_num}")
print(f" 告警行数:{len(alerts)}")
print(f"\n📊 关键词分布:")
for kw, count in keyword_counts.most_common():
print(f" {kw}: {count}次")
print(f"\n🔴 最近10条告警:")
for alert in alerts[-10:]:
print(f" 行{alert['line']}: {alert['content'][:80]}")
return alerts
# 使用
# analyze_log("/var/log/syslog")
# analyze_log("switch_log.txt", ["LOOP", "STP", "BPDU", "flapping"])
```
---
## 九、错误处理
```python
# try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("除零错误")
except (TypeError, ValueError) as e:
print(f"类型或值错误:{e}")
except Exception as e:
print(f"未知错误:{e}")
finally:
print("无论如何都会执行")
# 自定义异常
class DeviceError(Exception):
def __init__(self, device, message):
self.device = device
self.message = message
super().__init__(f"[{device}] {message}")
# 使用
try:
raise DeviceError("SW-Core-01", "连接超时")
except DeviceError as e:
print(e) # [SW-Core-01] 连接超时
```
---
## 十、免费学习资源
### 📚 在线教程
| 资源 | 说明 | 链接 |
|------|------|------|
| Python官方文档 | 最权威 | docs.python.org/zh-cn/3/ |
| 菜鸟教程 | 中文入门友好 | runoob.com/python3 |
| 廖雪峰Python教程 | 简洁实用 | liaoxuefeng.com/books/python |
| Real Python | 英文深度教程 | realpython.com |
| Python Tutor | 代码可视化 | pythontutor.com |
### 🎬 视频教程
| 资源 | 说明 |
|------|------|
| B站 黑马程序员Python | 免费完整体系课 |
| B站 小甲鱼Python | 轻松入门风格 |
| Coursera Python for Everybody | 密歇根大学免费课 |
| YouTube Corey Schafer | 英文最佳系列 |
### 🛠️ 练习平台
| 平台 | 说明 |
|------|------|
| LeetCode | 算法题(选简单开始) |
| Codewars | 游戏化编程练习 |
| Exercism | 有导师review |
| Project Euler | 数学+编程 |
### 💻 开发工具
| 工具 | 说明 |
|------|------|
| VS Code | 免费轻量,装Python插件 |
| PyCharm Community | 免费版功能够用 |
| Jupyter Notebook | 交互式,适合数据分析 |
| Thonny | 适合纯新手 |
---
## 十一、学习建议
1. **每天写代码** — 哪怕只写15分钟,保持手感最重要
2. **先抄后改** — 先跑通别人的代码,再修改理解
3. **项目驱动** — 学完基础后立刻做项目,不要只看视频
4. **善用print调试** — `print(f"{变量=}")` 是最快的调试方式
5. **读报错信息** — Python报错很清晰,从下往上看
6. **遇到问题先搜** — 99%的问题别人遇到过,Stack Overflow搜一下
7. **别追求完美** — 先跑通再优化,能用的代码 > 漂亮的代码