Python 基础语法
大约 9 分钟约 2780 字
Python 基础语法
简介
Python 是一门简洁优雅的通用编程语言,以可读性强、学习曲线平缓著称。广泛应用于 Web 开发、数据分析、AI/ML、自动化脚本等领域。本篇介绍 Python 的核心语法,帮助 .NET 开发者快速上手。
特点
变量与类型
基础类型
# 变量赋值(动态类型)
name = "张三" # str
age = 30 # int
height = 1.75 # float
is_active = True # bool
score = None # NoneType
# 类型检查
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
# 类型注解(Python 3.6+)
def greet(user_name: str, user_age: int) -> str:
return f"Hello, {user_name}, age {user_age}"
# 字符串操作
text = "Hello, World"
print(text.upper()) # HELLO, WORLD
print(text.lower()) # hello, world
print(text.split(", ")) # ['Hello', 'World']
print(text.replace("World", "Python")) # Hello, Python
print(f"姓名: {name}, 年龄: {age}") # f-string 格式化运算符
# 算术运算
print(10 / 3) # 3.3333 浮点除法
print(10 // 3) # 3 整除
print(10 % 3) # 1 取模
print(2 ** 10) # 1024 幂运算
# 比较运算
print(1 == 1) # True
print(1 != 2) # True
print(1 < 2) # True
# 逻辑运算
print(True and False) # False
print(True or False) # True
print(not True) # False
# 成员运算
print(3 in [1, 2, 3]) # True
print("a" not in "hello") # True流程控制
条件判断
# if/elif/else
score = 85
if score >= 90:
grade = "优秀"
elif score >= 80:
grade = "良好"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
# 三元表达式
status = "成年" if age >= 18 else "未成年"
# match-case(Python 3.10+)
command = "start"
match command:
case "start":
print("启动服务")
case "stop":
print("停止服务")
case "restart":
print("重启服务")
case _:
print("未知命令")循环
# for 循环
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(fruit)
# 带索引遍历
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# range 循环
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)
# while 循环
count = 0
while count < 5:
count += 1
# 列表推导式
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]
# 字典推导式
word_len = {w: len(w) for w in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}
# break/continue
for i in range(10):
if i == 3:
continue # 跳过 3
if i == 7:
break # 到 7 停止
print(i)函数
函数定义
# 基本函数
def add(a: int, b: int) -> int:
return a + b
# 默认参数
def greet(name: str, greeting: str = "你好") -> str:
return f"{greeting}, {name}"
print(greet("张三")) # 你好, 张三
print(greet("李四", "Hello")) # Hello, 李四
# 可变参数
def summarize(*args, **kwargs):
print(f"位置参数: {args}")
print(f"关键字参数: {kwargs}")
summarize(1, 2, 3, name="test", age=20)
# 位置参数: (1, 2, 3)
# 关键字参数: {'name': 'test', 'age': 20}
# Lambda 表达式
square = lambda x: x ** 2
multiply = lambda a, b: a * b
# map/filter/reduce
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers)) # [2, 4, 6, 8, 10]
odds = list(filter(lambda x: x % 2 != 0, numbers)) # [1, 3, 5]
from functools import reduce
total = reduce(lambda a, b: a + b, numbers) # 15装饰器
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:.3f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "done"
result = slow_function() # slow_function 执行耗时: 1.001s模块与包
导入
# 标准库导入
import os
import json
from datetime import datetime, timedelta
from pathlib import Path
# 使用
print(os.getcwd()) # 当前目录
print(datetime.now().strftime("%Y-%m-%d")) # 2024-01-15
data = {"name": "张三", "age": 30}
json_str = json.dumps(data, ensure_ascii=False)
parsed = json.loads(json_str)
# pathlib 路径操作
p = Path("/data/reports/2024")
print(p.parent) # /data/reports
print(p.stem) # 2024
print(p.suffix) # (空)
p.mkdir(parents=True, exist_ok=True) # 创建目录数据结构进阶
字典高级操作
# 字典推导式与合并
prices = {"苹果": 5.5, "香蕉": 3.0, "橙子": 4.5}
discounted = {k: round(v * 0.9, 2) for k, v in prices.items()}
# 字典合并(Python 3.9+)
config = {"debug": True}
defaults = {"host": "localhost", "port": 8080}
merged = config | defaults # Python 3.9+ 合并语法
# {"debug": True, "host": "localhost", "port": 8080}
# setdefault 和 defaultdict 避免 KeyError
from collections import defaultdict, Counter
# 统计词频
words = ["python", "java", "python", "go", "python", "java"]
word_count = Counter(words)
print(word_count.most_common(2)) # [('python', 3), ('java', 2)]
# 分组数据
students = [
{"name": "张三", "class": "A", "score": 85},
{"name": "李四", "class": "B", "score": 92},
{"name": "王五", "class": "A", "score": 78},
]
groups = defaultdict(list)
for s in students:
groups[s["class"]].append(s["name"])
print(dict(groups)) # {'A': ['张三', '王五'], 'B': ['李四']}集合与高级操作
# 集合运算
tags_a = {"python", "flask", "rest", "api"}
tags_b = {"python", "django", "web", "api"}
print(tags_a & tags_b) # 交集: {'python', 'api'}
print(tags_a | tags_b) # 并集: {'python', 'flask', 'rest', 'api', 'django', 'web'}
print(tags_a - tags_b) # 差集: {'flask', 'rest'}
# 去重保持顺序
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = list(dict.fromkeys(items)) # [3, 1, 4, 5, 9, 2, 6]
# 切片高级用法
data = list(range(10))
print(data[2:8:2]) # [2, 4, 6] 步长切片
print(data[::-1]) # [9, 8, 7, ...] 反转
print(data[-3:]) # [7, 8, 9] 最后三个异常处理
异常捕获与自定义异常
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (TypeError, ValueError) as e:
print(f"类型或值错误: {e}")
else:
print("没有异常时执行")
finally:
print("无论如何都执行")
# 自定义异常层次
class AppError(Exception):
"""应用基础异常"""
def __init__(self, message: str, code: int = 500):
self.message = message
self.code = code
super().__init__(f"[{code}] {message}")
class NotFoundError(AppError):
def __init__(self, resource: str, resource_id):
super().__init__(f"{resource} {resource_id} 不存在", code=404)
class PermissionDeniedError(AppError):
def __init__(self, action: str):
super().__init__(f"权限不足,无法执行: {action}", code=403)
# 使用自定义异常
def get_user(user_id: int):
if user_id <= 0:
raise ValueError("用户 ID 必须为正整数")
if user_id > 100:
raise NotFoundError("用户", user_id)
return {"id": user_id, "name": "张三"}
# 捕获异常链
try:
get_user(999)
except AppError as e:
print(f"应用错误: {e.message}, 状态码: {e.code}")
except ValueError as e:
print(f"参数错误: {e}")上下文管理器
# with 语句与上下文管理器
class Timer:
"""计时上下文管理器"""
def __enter__(self):
import time
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
self.elapsed = time.perf_counter() - self.start
print(f"耗时: {self.elapsed:.4f}s")
return False
with Timer() as t:
sum(range(10_000_000))
print(f"结果耗时: {t.elapsed:.4f}s")
# suppress 上下文管理器
from contextlib import suppress
with suppress(FileNotFoundError):
with open("不存在的文件.txt") as f:
content = f.read()
# 文件不存在也不会抛异常常用标准库
collections 与 itertools
from collections import namedtuple, deque, OrderedDict
from itertools import chain, groupby, product
# 命名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y, p[0]) # 3 4 3
# 双端队列(高效的两端操作)
queue = deque([1, 2, 3])
queue.append(4) # 右端追加
queue.appendleft(0) # 左端追加
queue.pop() # 右端弹出
queue.popleft() # 左端弹出
# 链式迭代
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(chain(list1, list2)) # [1, 2, 3, 4, 5, 6]
# 笛卡尔积
colors = ["红", "蓝"]
sizes = ["S", "M", "L"]
for c, s in product(colors, sizes):
print(f"{c}-{s}") # 红-S, 红-M, 红-L, 蓝-S, ...
# 分组(需要先排序)
data = [("A", 90), ("B", 85), ("A", 78), ("B", 92)]
data.sort(key=lambda x: x[0])
for key, group in groupby(data, key=lambda x: x[0]):
print(f"{key}: {[item[1] for item in group]}")正则表达式
import re
# 常用正则匹配
text = "联系邮箱: test@example.com, 电话: 13800138000"
# 提取邮箱
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
print(emails) # ['test@example.com']
# 提取手机号
phones = re.findall(r'1[3-9]\d{9}', text)
print(phones) # ['13800138000']
# 替换敏感信息
masked = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', text)
print(masked) # 联系邮箱: test@example.com, 电话: 138****8000
# 分割
csv_line = "a,b,,c,d"
parts = re.split(r',+', csv_line)
print(parts) # ['a', 'b', 'c', 'd']
# 编译正则提升性能
pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')
if pattern.match("2024-01-15"):
print("日期格式正确")Python vs C# 对比
| 特性 | Python | C# |
|---|---|---|
| 类型系统 | 动态类型 | 静态类型 |
| 代码块 | 缩进 | 花括号 {} |
| 主函数 | 直接执行 | static void Main |
| 包管理 | pip | NuGet |
| 虚拟环境 | venv | - |
| 列表 | list [1,2,3] | List<T> |
| 字典 | dict | Dictionary<K,V> |
| 属性 | @property | get/set |
| 异步 | async/await | async/await |
| 接口 | 鸭子类型 | interface |
优点
缺点
总结
Python 基础语法核心:动态类型变量、缩进代码块、列表推导式、装饰器。与 C# 的主要区别:动态类型、缩进语法、鸭子类型、无需编译。常用内置模块:os(系统操作)、json(序列化)、datetime(时间)、pathlib(路径)。开发建议使用虚拟环境(venv),用类型注解提升代码可维护性。
关键知识点
- 先区分这篇内容属于语法能力、工程能力,还是生态工具能力。
- Python 的开发效率来自生态,但可维护性来自结构、测试和规范。
- 脚本一旦进入长期维护,就必须按项目来治理。
- 框架与语言特性类主题要同时理解运行方式和工程组织方式。
项目落地视角
- 统一虚拟环境、依赖锁定、格式化和日志方案。
- 把入口、配置、业务逻辑和工具函数拆开,避免单文件膨胀。
- 对网络请求、文件读写和数据处理结果做异常与样本校验。
- 明确项目入口、配置管理、依赖管理、日志和测试策略。
常见误区
- 把临时脚本直接当生产代码使用。
- 忽略依赖版本、编码、路径和时区差异。
- 只会写 happy path,没有补超时、重试和资源释放。
- 把 notebook 或脚本风格直接带入长期维护项目。
进阶路线
- 把类型注解、测试、打包和部署纳入统一工程流程。
- 继续向异步、性能、数据管线和框架源码层深入。
- 把常用脚本抽成可复用库或 CLI 工具,而不是复制粘贴。
- 继续补齐部署、打包、监控和性能调优能力。
适用场景
- 当你准备把《Python 基础语法》真正落到项目里时,最适合先在一个独立模块或最小样例里验证关键路径。
- 适合脚本自动化、数据处理、Web 开发和测试工具建设。
- 当需求强调快速迭代和丰富生态时,Python 往往能快速起步。
落地建议
- 统一使用虚拟环境与依赖锁定,避免环境漂移。
- 对核心函数补类型注解、异常处理和日志,减少“脚本黑盒”。
- 一旦脚本进入生产链路,及时补测试和监控。
排错清单
- 先确认当前解释器、虚拟环境和依赖版本是否正确。
- 检查编码、路径、时区和第三方库行为差异。
- 排查同步阻塞、数据库连接未释放或网络请求无超时。
复盘问题
- 如果把《Python 基础语法》放进你的当前项目,最先要验证的输入、输出和失败路径分别是什么?
- 《Python 基础语法》最容易在什么规模、什么边界条件下暴露问题?你会用什么指标或日志去确认?
- 相比默认实现或替代方案,采用《Python 基础语法》最大的收益和代价分别是什么?
