Python 语法完全教程(覆盖主流项目所需)
·
Python 语法完全教程(覆盖主流项目所需)
第一部分:基础语法
1.1 变量与基本数据类型
# Python 是动态类型,变量无需声明类型
name = "Alice" # str 字符串
age = 25 # int 整数
height = 1.68 # float 浮点数
is_student = True # bool 布尔(注意首字母大写 True/False)
nothing = None # NoneType 空值(相当于 Java 的 null)
# 多重赋值
x, y, z = 1, 2, 3
a = b = c = 0
# 交换变量(Python 特色,不需要临时变量)
x, y = y, x
# 查看类型
print(type(age)) # <class 'int'>
print(isinstance(age, int)) # True
1.2 数字与运算符
# 算术运算
10 / 3 # 3.333... 真除法,结果是 float
10 // 3 # 3 整除(向下取整)
10 % 3 # 1 取余
2 ** 10 # 1024 幂运算
abs(-5) # 5 绝对值
round(3.14159, 2) # 3.14 四舍五入
# 比较返回布尔
5 > 3 # True
# 逻辑运算符用单词,不是 && || !
True and False # False
True or False # True
not True # False
# 链式比较(Python 特色)
1 < age < 100 # 等价于 1 < age and age < 100
1.3 字符串(项目高频)
s = "Hello, World"
# 索引与切片 [起始:结束:步长]
s[0] # 'H'
s[-1] # 'd' 负索引从尾部
s[0:5] # 'Hello' 左闭右开
s[7:] # 'World'
s[::-1] # 反转字符串
s[::2] # 隔一个取一个
# f-string 格式化(最常用,Python 3.6+)
name, age = "Bob", 30
print(f"我叫{name},今年{age}岁")
print(f"明年{age + 1}岁") # 表达式
print(f"价格:{3.14159:.2f}") # 保留2位小数
print(f"{age:>5}") # 右对齐占5位
print(f"{name=}") # 调试:输出 name='Bob'
# 常用方法
s.upper() # 转大写
s.lower() # 转小写
s.strip() # 去首尾空白
s.replace("o", "0") # 替换
s.split(",") # 按逗号分割成列表 ['Hello', ' World']
",".join(["a", "b"]) # 列表拼接成字符串 'a,b'
s.startswith("Hello") # True
s.find("World") # 返回索引,找不到返回 -1
len(s) # 长度
"123".isdigit() # 是否全数字
# 多行字符串
text = """第一行
第二行"""
第二部分:容器类型(核心中的核心)
2.1 列表 list(可变、有序)
nums = [3, 1, 4, 1, 5, 9]
# 增删改查
nums.append(2) # 尾部添加
nums.insert(0, 99) # 指定位置插入
nums.extend([6, 7]) # 合并另一个列表
nums.remove(1) # 删除第一个值为1的元素
nums.pop() # 删除并返回最后一个
nums.pop(0) # 删除并返回索引0
del nums[0] # 按索引删除
nums[0] = 100 # 修改
# 查询
nums.index(4) # 元素4的索引
nums.count(1) # 1出现的次数
4 in nums # 是否存在
# 排序
nums.sort() # 原地升序
nums.sort(reverse=True) # 原地降序
sorted(nums) # 返回新列表,不改原列表
sorted(nums, key=lambda x: -x) # 自定义排序规则
nums.reverse() # 原地反转
# 切片(和字符串一样)
nums[1:3]
nums[:] # 浅拷贝整个列表
2.2 元组 tuple(不可变、有序)
point = (3, 4)
x, y = point # 解包
# 单元素元组必须带逗号
single = (5,) # 是元组
not_tuple = (5) # 这是 int!
# 元组不可修改,常用于函数返回多个值
def get_min_max(nums):
return min(nums), max(nums) # 返回元组
low, high = get_min_max([3, 1, 4])
2.3 字典 dict(键值对,项目超高频)
user = {"name": "Alice", "age": 25, "city": "Beijing"}
# 访问
user["name"] # 'Alice',键不存在会报错
user.get("email") # None,键不存在返回 None(安全)
user.get("email", "无") # 提供默认值
# 增改
user["email"] = "a@x.com" # 新增或修改
user.update({"age": 26, "phone": "123"}) # 批量更新
# 删除
del user["city"]
user.pop("phone", None) # 安全删除
# 遍历
for key in user: # 遍历键
print(key)
for value in user.values(): # 遍历值
print(value)
for key, value in user.items(): # 遍历键值对(最常用)
print(f"{key}: {value}")
# 判断键
"name" in user # True
# 字典常用方法
user.keys() # 所有键
user.values() # 所有值
user.setdefault("score", 0) # 键不存在才设置
2.4 集合 set(去重、无序)
s = {1, 2, 3, 3, 2} # {1, 2, 3} 自动去重
s.add(4)
s.remove(1)
s.discard(99) # 不存在也不报错
# 集合运算(去重/交并差很方便)
a = {1, 2, 3}
b = {2, 3, 4}
a | b # 并集 {1,2,3,4}
a & b # 交集 {2,3}
a - b # 差集 {1}
a ^ b # 对称差 {1,4}
# 列表去重技巧
unique = list(set([1, 1, 2, 3]))
第三部分:控制流
3.1 条件判断
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
# 三元表达式
status = "及格" if score >= 60 else "不及格"
# Python 没有 switch,3.10+ 有 match
match grade:
case "A":
print("优秀")
case "B" | "C": # 多值匹配
print("良好")
case _: # 默认
print("其他")
# 真值判断:空容器、0、None、空字符串都是 False
if not nums: # 列表为空
print("空列表")
if name: # 字符串非空
print("有名字")
3.2 循环
# 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)
# 遍历容器
for item in [1, 2, 3]:
print(item)
# enumerate 同时拿索引和值(高频)
for index, value in enumerate(["a", "b", "c"]):
print(f"{index}: {value}")
# zip 同时遍历多个(高频)
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}")
# while
count = 0
while count < 5:
count += 1
if count == 2:
continue # 跳过本次
if count == 4:
break # 终止循环
# for-else(循环正常结束才执行 else)
for n in [1, 2, 3]:
if n == 99:
break
else:
print("没找到99")
3.3 推导式(Python 灵魂,必须掌握)
# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0] # 带过滤
matrix = [[i*j for j in range(3)] for i in range(3)] # 嵌套
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}
# 集合推导式
unique_lengths = {len(w) for w in ["a", "bb", "cc"]}
# 生成器表达式(省内存,用括号)
gen = (x**2 for x in range(1000000)) # 不立即计算
第四部分:函数
4.1 函数定义与参数
# 基本定义
def greet(name):
return f"Hello, {name}"
# 默认参数
def power(base, exp=2):
return base ** exp
power(3) # 9
power(3, 3) # 27
# 关键字参数(调用时指定名字,顺序无所谓)
def create_user(name, age, city):
return f"{name}, {age}, {city}"
create_user(age=25, name="Bob", city="SH")
# *args 接收任意位置参数(变成元组)
def total(*args):
return sum(args)
total(1, 2, 3, 4) # 10
# **kwargs 接收任意关键字参数(变成字典)
def config(**kwargs):
for k, v in kwargs.items():
print(f"{k}={v}")
config(host="localhost", port=8080)
# 综合用法(项目里框架常见)
def func(a, b, *args, **kwargs):
pass
# 仅关键字参数(* 之后必须用关键字传)
def connect(host, *, timeout=30):
pass
connect("localhost", timeout=10) # timeout 必须写名字
4.2 lambda、闭包、装饰器
# lambda 匿名函数
add = lambda x, y: x + y
add(3, 5) # 8
# 常用于排序/过滤的 key
data = [("a", 3), ("b", 1), ("c", 2)]
data.sort(key=lambda item: item[1]) # 按第二个元素排序
# 高阶函数
list(map(lambda x: x*2, [1, 2, 3])) # [2,4,6]
list(filter(lambda x: x > 1, [0, 1, 2])) # [2]
# 闭包:内层函数捕获外层变量
def make_counter():
count = 0
def counter():
nonlocal count # 声明修改外层变量
count += 1
return count
return counter
c = make_counter()
c() # 1
c() # 2
# 装饰器(框架核心特性,如 Flask 的 @app.route)
import functools
def log(func):
@functools.wraps(func) # 保留原函数元信息
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__}")
result = func(*args, **kwargs)
print(f"返回 {result}")
return result
return wrapper
@log
def add(a, b):
return a + b
add(2, 3) # 自动打印日志
# 带参数的装饰器
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
try:
return func(*args, **kwargs)
except Exception:
continue
return wrapper
return decorator
@retry(times=3)
def fetch():
pass
第五部分:面向对象编程
5.1 类与对象
class Person:
# 类属性(所有实例共享)
species = "Human"
# 构造方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
self._secret = "私有约定" # 单下划线:约定私有
self.__private = "强私有" # 双下划线:名称改写
# 实例方法(第一个参数永远是 self)
def introduce(self):
return f"我是{self.name}"
# 类方法(操作类本身)
@classmethod
def create_baby(cls, name):
return cls(name, 0)
# 静态方法(不依赖实例或类)
@staticmethod
def is_adult(age):
return age >= 18
p = Person("Alice", 25)
print(p.introduce())
print(Person.is_adult(20))
baby = Person.create_baby("Tom")
5.2 继承与多态
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError # 抽象方法
class Dog(Animal):
def speak(self): # 重写
return "汪汪"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # 调用父类构造
self.color = color
def speak(self):
return "喵喵"
# 多态:同一接口不同实现
animals = [Dog("旺财"), Cat("咪咪", "白")]
for a in animals:
print(a.speak())
5.3 魔术方法与 property
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self): # print 时的显示
return f"Vector({self.x}, {self.y})"
def __repr__(self): # 调试显示
return self.__str__()
def __add__(self, other): # 重载 + 运算符
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # 重载 ==
return self.x == other.x and self.y == other.y
def __len__(self): # len() 调用
return 2
def __getitem__(self, i): # 支持索引 v[0]
return (self.x, self.y)[i]
v = Vector(1, 2) + Vector(3, 4)
print(v) # Vector(4, 6)
# property:把方法当属性用(getter/setter)
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self): # 像属性一样访问
return 3.14 * self._radius ** 2
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value): # 赋值时校验
if value < 0:
raise ValueError("半径不能为负")
self._radius = value
c = Circle(5)
print(c.area) # 不用加括号
c.radius = 10 # 触发 setter
5.4 dataclass(项目常用,省样板代码)
from dataclasses import dataclass, field
@dataclass
class User:
name: str
age: int = 0 # 默认值
tags: list = field(default_factory=list) # 可变默认值
def is_adult(self) -> bool:
return self.age >= 18
# 自动生成 __init__、__repr__、__eq__
u = User("Alice", 25)
print(u) # User(name='Alice', age=25, tags=[])
print(u == User("Alice", 25)) # True
第六部分:异常处理
try:
result = 10 / 0
value = int("abc")
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (ValueError, TypeError) as e: # 捕获多种
print(f"类型/值错误: {e}")
except Exception as e: # 兜底
print(f"其他错误: {e}")
else:
print("没有异常才执行")
finally:
print("无论如何都执行(清理资源)")
# 主动抛出异常
def set_age(age):
if age < 0:
raise ValueError("年龄不能为负")
# 自定义异常
class BizException(Exception):
def __init__(self, code, message):
self.code = code
self.message = message
super().__init__(message)
raise BizException(500, "业务错误")
第七部分:迭代器与生成器
# 生成器函数(用 yield,省内存,处理大数据/流式)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a # 每次产出一个值,暂停
a, b = b, a + b
for num in fibonacci(10):
print(num)
# 生成器只能遍历一次
gen = fibonacci(5)
list(gen) # [0,1,1,2,3]
list(gen) # [] 已耗尽
# 自定义迭代器
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
for n in Countdown(3):
print(n) # 3, 2, 1
第八部分:类型注解(现代项目标配)
from typing import Optional, Union, Any, Callable
# 基本注解
def greet(name: str, age: int = 0) -> str:
return f"{name}, {age}"
# 容器注解(Python 3.9+ 可直接用小写)
def process(items: list[int]) -> dict[str, int]:
return {"count": len(items)}
# Optional 表示可能是 None
def find_user(id: int) -> Optional[str]:
return None
# Union 表示多种类型(3.10+ 可用 |)
def parse(value: Union[str, int]) -> str: # 或 str | int
return str(value)
# Callable 函数类型
def apply(func: Callable[[int], int], x: int) -> int:
return func(x)
# 变量注解
name: str = "Alice"
scores: list[int] = [90, 85]
第九部分:文件与上下文管理器
# with 自动管理资源(自动关闭文件)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # 读全部
# lines = f.readlines() # 读成列表
# for line in f: ... # 逐行(省内存)
# 写文件
with open("out.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
f.writelines(["a\n", "b\n"])
# 追加模式 "a",二进制 "rb"/"wb"
# JSON(项目超高频)
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2) # 对象转字符串
obj = json.loads(json_str) # 字符串转对象
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
with open("data.json", encoding="utf-8") as f:
obj = json.load(f)
# 自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"耗时 {time.time() - start}s")
with timer():
# 做一些事
pass
第十部分:模块与包
# 导入方式
import math
from math import pi, sqrt
from math import sqrt as square_root # 别名
import numpy as np # 常见约定
# 使用
math.pi
sqrt(16)
# 模块的 __name__ 判断(脚本入口)
def main():
print("运行主程序")
if __name__ == "__main__": # 直接运行时才执行,被导入时不执行
main()
# 包结构示例
# myproject/
# __init__.py # 标识这是包
# utils/
# __init__.py
# helper.py
# 导入:from myproject.utils.helper import some_func
第十一部分:异步编程(高并发项目必备)
import asyncio
# 定义协程
async def fetch_data(name, delay):
print(f"{name} 开始")
await asyncio.sleep(delay) # 模拟IO等待,不阻塞
print(f"{name} 完成")
return f"{name}的数据"
# 并发执行多个任务
async def main():
# 串行(慢)
# r1 = await fetch_data("A", 1)
# r2 = await fetch_data("B", 1)
# 并发(快,同时进行)
results = await asyncio.gather(
fetch_data("A", 1),
fetch_data("B", 2),
fetch_data("C", 1),
)
print(results)
asyncio.run(main()) # 启动事件循环
第十二部分:标准库高频工具
# collections
from collections import defaultdict, Counter, deque, namedtuple
d = defaultdict(list) # 访问不存在的键自动创建
d["a"].append(1) # 不报错
c = Counter("aabbbcccc") # 计数 {'c':4, 'b':3, 'a':2}
c.most_common(2) # 出现最多的2个
dq = deque([1, 2, 3]) # 双端队列
dq.appendleft(0) # 左侧添加(高效)
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
p.x # 1
# itertools
from itertools import chain, combinations, groupby, product
list(chain([1,2], [3,4])) # [1,2,3,4] 连接
list(combinations([1,2,3], 2)) # [(1,2),(1,3),(2,3)] 组合
# datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S") # 格式化
datetime.strptime("2026-01-01", "%Y-%m-%d") # 解析
tomorrow = now + timedelta(days=1)
# os / pathlib(路径操作,推荐 pathlib)
from pathlib import Path
p = Path("data") / "file.txt" # 路径拼接
p.exists()
p.suffix # '.txt'
p.parent # 父目录
list(Path(".").glob("*.py")) # 找所有py文件
# re 正则
import re
re.match(r"\d+", "123abc") # 从头匹配
re.search(r"\d+", "abc123") # 任意位置
re.findall(r"\d+", "a1b2c3") # ['1','2','3']
re.sub(r"\d", "*", "a1b2") # 'a*b*'
第十三部分:项目实战常用第三方库速览
# requests —— HTTP 请求(爬虫/调API)
import requests
resp = requests.get("https://api.example.com", params={"q": "x"})
resp = requests.post("https://api.example.com", json={"key": "value"})
data = resp.json()
# pydantic —— 数据校验(FastAPI/AI项目标配)
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
user = User(name="Alice", age="25") # 自动转换+校验
# FastAPI —— Web框架(写API)
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{id}")
def get_user(id: int):
return {"id": id}
# 数据科学三件套
import numpy as np # 数值计算
import pandas as pd # 数据分析
# df = pd.read_csv("data.csv")
附:环境与工程化(绕不开)
# 虚拟环境(隔离依赖)
python -m venv venv # 创建
source venv/bin/activate # 激活(Linux/Mac)
venv\Scripts\activate # 激活(Windows)
# 包管理
pip install requests # 安装
pip install -r requirements.txt # 批量安装
pip freeze > requirements.txt # 导出依赖
# 现代工具(推荐)
# uv —— 极快的包管理器,正在成为主流
# poetry —— 依赖+打包管理
Python vs Java 关键差异(结合你的背景)
| 维度 | Java | Python |
|---|---|---|
| 类型 | 静态强类型 | 动态类型(可选注解) |
| 代码块 | {} 大括号 |
缩进(4空格) |
| 分号 | 必须 | 不需要 |
| 变量声明 | int x = 1 |
x = 1 |
| null | null |
None |
| 逻辑运算 | && || ! |
and or not |
| 三元 | a ? b : c |
b if a else c |
| 遍历 | for(int i...) |
for i in range() |
| 接口 | interface |
抽象基类/鸭子类型 |
| 私有 | private |
_ 约定 / __ 改写 |
| Getter/Setter | 手写方法 | @property |
更多推荐

所有评论(0)