Python 语言概述
1. Python 特点
- 解释型语言:无需编译,直接运行
- 动态类型:变量类型在运行时确定
- 面向对象:支持面向对象编程范式
- 语法简洁:代码可读性强,学习曲线平缓
- 丰富的标准库:内置大量实用模块
2. Python 应用领域
Web 开发:Django, Flask
数据科学:NumPy, Pandas
机器学习:Scikit-learn, TensorFlow
自动化运维:Ansible
爬虫:Scrapy
桌面应用:PyQt, Tkinter
基础语法与数据类型
1. 变量与赋值
# 变量命名规则 variable_name = "value"
# 小写加下划线 CONSTANT_NAME = 100 # 全大写表示常量
_class_name = None # 前置下划线表示内部使用
# 多重赋值 a, b, c = 1, 2, 3
x = y = z = 0
# 解包赋值 data = [1, 2, 3]
first, second, third = data
2. 基本数据类型
数值类型
# 整数 int_num = 10
binary_num = 0b1010 # 二进制
octal_num = 0o12 # 八进制
hex_num = 0xA # 十六进制
# 浮点数 float_num = 3.14
scientific = 2.5e3 # 2500.0
# 复数 complex_num = 3 + 4j
# 布尔值 bool_true = True
bool_false = False
字符串
# 三种引号 str1 = '单引号'
str2 = "双引号"
str3 = '''三引号 可以跨多行'''
# 字符串操作 text = "Python"
print(len(text)) # 长度 6
print(text[0]) # 索引 P
print(text[1:4]) # 切片 yth
print(text.upper()) # 大写 PYTHON
print(text.lower()) # 小写 python
print(text.replace('P', 'J')) # 替换 Jython
name = "小明"
age = 20
print(f"{name}今年{age}岁")
列表 (List)
# 创建列表 my_list = [1, 2, 3, 'a', 'b']
nested_list = [[1, 2], [3, 4]]
# 列表操作 my_list.append(4) # 添加元素 [1, 2, 3, 'a', 'b', 4]
my_list.insert(1, 'x') # 插入元素 [1, 'x', 2, 3, 'a', 'b', 4]
my_list.remove('a') # 删除元素 [1, 'x', 2, 3, 'b', 4]
popped = my_list.pop() # 弹出最后一个元素 [1, 'x', 2, 3, 'b']
my_list = ['a', 'b', 'c', 'd', 'w', 's']
my_list.sort() # 排序 ['a', 'b', 'c', 'd', 's', 'w']
my_list.reverse() # 反转 ['w', 's', 'd', 'c', 'b', 'a']
new_list = my_list.copy() # 浅拷贝 ['w', 's', 'd', 'c', 'b', 'a']
# 列表推导式 squares = [x**2 for x in range(10)] #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
filtered = [x for x in range(10) if x % 2 == 0] #[0, 2, 4, 6, 8]
元组 (Tuple)
# 创建元组 my_tuple = (1, 2, 3)
single_tuple = (1,) # 单个元素需要逗号
empty_tuple = () # 元组是不可变的
# my_tuple[0] = 10 # 错误!不能修改
# 解包 x, y, z = my_tuple
字典 (Dictionary)
# 创建字典 my_dict = {'name': '小明', 'age': 20, 'city': '北京'}
empty_dict = {}
# 字典操作 my_dict['gender'] = '男' # 添加/修改
value = my_dict.get('name') # 获取值
value = my_dict['name'] # 另一种获取方式
del my_dict['city'] # 删除键值对
# 遍历字典 for key, value in my_dict.items():
print(f"{key}: {value}")
# 字典推导式 squares = {x: x**2 for x in range(5)} #{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
集合 (Set)
# 创建集合 my_set = {1, 2, 3, 3} # 自动去重,结果为{1, 2, 3}
empty_set = set()
# 集合操作 set1 = {1, 2, 3}
set2 = {2, 3, 4}
union = set1 | set2 # 并集 {1, 2, 3, 4}
intersection = set1 & set2 # 交集 {2, 3}
difference = set1 - set2 # 差集 {1}
symmetric_diff = set1 ^ set2 # 对称差集 {1, 4}
# 集合推导式 even_squares = {x**2 for x in range(10) if x % 2 == 0} #{0, 64, 4, 36, 16}
3. 运算符
1. 算术运算符
a + b # 加法
a - b # 减法
a * b # 乘法
a / b # 除法 (返回浮点数)
a // b # 整除
a % b # 取余
a ** b # 幂运算
2. 比较运算符
a == b # 等于
a != b # 不等于
a > b # 大于
a < b # 小于
a >= b # 大于等于
a <= b # 小于等于
3. 逻辑运算符
a and b # 与
a or b # 或
not a # 非
4. 成员运算符
x in collection # 在序列中
x not in collection # 不在序列中
5. 身份运算符
x is y # 是同一个对象
x is not y # 不是同一个对象
4. 控制流
1. 条件语句
# if-elif-else score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
# 三元表达式 result = "及格" if score >= 60 else "不及格"
2. 循环语句
for 循环
# 遍历序列 fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 遍历字典 person = {'name': '小明', 'age': 20}
for key, value in person.items():
print(f"{key}: {value}")
# range 函数 for i in range(5): # 0 到 4
print(i)
for i in range(1, 10, 2): # 1 到 9,步长为 2
print(i)
# enumerate 获取索引 for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
while 循环
count = 0
while count < 5:
print(count)
count += 1
# 带 else 的 while 循环 count = 0
while count < 5:
print(count)
count += 1
else:
print("循环结束")
循环控制
# break - 跳出整个循环 for i in range(10):
if i == 5:
break
print(i)
# continue - 跳过当前迭代 for i in range(10):
if i % 2 == 0:
continue
print(i) # 只打印奇数
# pass - 占位符,什么都不做 for i in range(5):
pass # 暂时不写实现
5. 函数
1. 函数定义
def function_name(parameters):
"""函数文档字符串"""
# 函数体
return result
2. 函数参数
# 位置参数 def greet(name, message):
return f"{message}, {name}!"
# 默认参数 def greet(name, message="你好"):
return f"{message}, {name}!"
# 关键字参数 greet(name="小明", message="Hello")
# 可变位置参数 (*args) def sum_all(*numbers):
return sum(numbers)
sum_all(1, 2, 3, 4, 5)
# 可变关键字参数 (**kwargs) def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="小明", age=20, city="北京")
# 参数组合 def complex_func(a, b, *args, c=10, **kwargs):
pass
3. 返回值
# 返回单个值 def square(x):
return x ** 2
# 返回多个值 (实际上是返回元组) def min_max(numbers):
return min(numbers), max(numbers)
min_val, max_val = min_max([1, 5, 3, 9, 2])
# 返回 None (隐式) def do_nothing():
pass
result = do_nothing() # result 为 None
4. 作用域
# 局部变量 def my_func():
local_var = 10 # 局部变量
print(local_var)
# 全局变量 global_var = 100
def access_global():
global global_var # 声明使用全局变量
global_var = 200
print(global_var)
# 嵌套函数 def outer():
x = 10
def inner():
nonlocal x # 声明使用外层函数的变量
x = 20
print(x)
inner()
print(x)
5. 匿名函数 (Lambda)
# 基本语法 lambda arguments: expression
# 示例 square = lambda x: x ** 2
print(square(5)) # 25
# 与内置函数结合使用 numbers = [1, 5, 3, 8, 2]
sorted_numbers = sorted(numbers, key=lambda x: x % 3) #[3, 1, 5, 8, 2]
6. 高阶函数
# map - 对每个元素应用函数 numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) #[1, 4, 9, 16]
# filter - 过滤元素 even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) #[2, 4]
# reduce - 累积计算 from functools import reduce
product = reduce(lambda x, y: x * y, numbers) #24
6. 文件相关操作
文件操作是 Python 核心实用技能,用于读取/写入文本、配置、日志等数据。核心流程:打开文件 → 操作文件(读/写)→ 关闭文件,推荐使用 with 语句自动管理文件生命周期(无需手动关闭)。
1. 核心基础:文件打开与关闭
关键函数:open()
语法:open(file, mode='r', encoding=None)
file:文件路径(绝对路径/相对路径)mode:打开模式(核心参数,见下表)encoding:编码格式(推荐utf-8,避免中文乱码)
常用打开模式
| 模式 | 作用 | 读写权限 | 若文件不存在 | 指针位置 |
|---|---|---|---|---|
| r | 只读(默认) | 仅读 | 报错 FileNotFoundError | 文件开头 |
| w | 写入(覆盖) | 仅写 | 创建文件 | 文件开头(清空原有内容) |
| a | 追加写入 | 仅写 | 创建文件 | 文件末尾 |
| r+ | 读写 | 读写 | 报错 | 文件开头 |
| w+ | 读写(覆盖) | 读写 | 创建文件 | 文件开头(清空原有内容) |
| a+ | 读写(追加) | 读写 | 创建文件 | 文件末尾 |
| rb/wb | 二进制读写(如图片/视频) | 对应权限 | 创建文件 | 文件末尾 |
两种打开方式(推荐第二种)
方式 1:手动打开 + 关闭(需 try-except 保证关闭)
# 手动管理文件(不推荐,容易遗漏 close()) file = None
try:
# 打开文件(utf-8 编码避免中文乱码) file = open("test.txt", mode="w", encoding="utf-8")
file.write("手动打开文件测试") # 写入内容
finally:
if file:
file.close() # 必须关闭,释放资源
方式 2:with 语句(自动关闭,推荐)
with 会在代码块结束后自动关闭文件,即使出现异常也能保证资源释放:
# 自动管理文件(推荐) with open("test.txt", mode="w", encoding="utf-8") as file:
file.write("with 语句自动关闭文件") # 代码块结束后自动 close()
3. 核心操作:读文件(r/r+/a+ 模式)
常用读方法:read()、readline()、readlines()、逐行遍历(推荐大文件)
1. read(size):读取指定字节数(默认读全部)
with open("test.txt", mode="r", encoding="utf-8") as file:
content = file.read() # 读全部内容
# content = file.read(10) # 读前 10 个字节(中文占 3 个字节,需注意)
print("读取结果:", content)
2. readline():逐行读取(每次读 1 行,含换行符 `
`)
with open("test.txt", mode="r", encoding="utf-8") as file:
line1 = file.readline() # 读第 1 行
line2 = file.readline() # 读第 2 行
print("第 1 行:", line1.strip()) # strip() 去除换行符/空格
print("第 2 行:", line2.strip())
3. readlines():读取所有行(返回列表,每行是元素)
with open("test.txt", mode="r", encoding="utf-8") as file:
lines = file.readlines() # 返回列表:["行 1\n", "行 2\n", ...]
# 遍历列表处理每行 for line in lines:
print("行内容:", line.strip())
4. 逐行遍历(处理大文件不占内存)
直接用 for 循环遍历文件对象,一行一行读,适合 GB 级大文件:
# 大文件读取(最优方案) with open("large_file.txt", mode="r", encoding="utf-8") as file:
for line in file: # 逐行读取,不加载全部内容到内存
print("处理行:", line.strip())
4. 核心操作:写文件(w/a/r+/w+ 模式)
常用写方法:write()、writelines()
1. write(str):写入字符串(需手动加换行符 `
`)
# 1. w 模式:覆盖写入(清空原有内容) with open("write_test.txt", mode="w", encoding="utf-8") as file:
file.write("第一行内容\n") # \n 表示换行
file.write("第二行内容(w 模式覆盖原有)\n")
# 2. a 模式:追加写入(在文件末尾添加,不覆盖) with open("write_test.txt", mode="a", encoding="utf-8") as file:
file.write("第三行内容(a 模式追加)\n")
2. writelines(iterable):写入可迭代对象(列表/元组等)
需确保元素是字符串,且手动加换行符:
lines = [
"Python 文件操作\n",
"writelines 写入列表\n",
"每个元素是字符串\n"
]
with open("write_lines.txt", mode="w", encoding="utf-8") as file:
file.writelines(lines) # 批量写入列表内容
5. 进阶操作:文件指针与定位
文件指针:记录当前读写位置(类似文本编辑器的光标)
tell():获取当前指针位置(字节数)seek(offset, whence):移动指针offset:偏移量(正数向右移,负数向左移)whence:基准位置(0 = 文件开头,1 = 当前位置,2 = 文件末尾)
with open("pointer_test.txt", mode="r+", encoding="utf-8") as file:
# 1. 初始指针在开头(0 字节) print("初始指针位置:", file.tell()) # 输出:0
# 2. 读 5 个字符(每个中文 3 字节,英文 1 字节) content = file.read(5)
print("读取内容:", content)
print("读后指针位置:", file.tell()) # 输出:5(假设是英文)
# 3. 指针移回文件开头(offset=0,whence=0) file.seek(0, 0)
print("移回开头后指针:", file.tell()) # 输出:0
# 4. 指针移到文件末尾(offset=0,whence=2) file.seek(0, 2)
print("移到末尾后指针:", file.tell()) # 输出:文件总字节数
6. 总结
- 最佳实践:优先用
with open(...)语句,自动管理文件关闭; - 编码统一:读写文本文件时指定
encoding="utf-8",避免中文乱码; - 模式选择:
- 读文件:
r(仅读)、r+(读写); - 写文件:
w(覆盖)、a(追加); - 二进制文件:
rb/wb(图片/视频等);
- 读文件:
- 大文件处理:用
for line in file逐行读取,不占内存; - 异常处理:捕获
FileNotFoundError、PermissionError等常见错误,提升程序健壮性。
7. 异常处理
1. 基本语法
try:
# 可能引发异常的代码 result = 10 / 0
except ZeroDivisionError: # 处理特定异常
print("不能除以零")
except (TypeError, ValueError) as e: # 处理多个异常
print(f"类型或值错误:{e}")
except Exception as e: # 处理所有其他异常
print(f"发生错误:{e}")
else: # 没有异常时执行
print("操作成功")
finally: # 无论是否发生异常都会执行
print("清理资源")
2. 常见内置异常
# 基础异常类 BaseException
# ├─ SystemExit
# ├─ KeyboardInterrupt
# ├─ GeneratorExit
# └─ Exception
# ├─ ArithmeticError
# │ ├─ ZeroDivisionError
# │ └─ OverflowError
# ├─ LookupError
# │ ├─ IndexError
# │ └─ KeyError
# ├─ TypeError
# ├─ ValueError
# ├─ FileNotFoundError
# └─ ...
3. 抛出异常
def validate_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age > 150:
raise ValueError("年龄不合理")
return True
# 自定义异常 class MyCustomError(Exception):
def __init__(self, message):
super().__init__(message)
self.custom_data = "额外的数据"
try:
raise MyCustomError("自定义错误")
except MyCustomError as e:
print(e)
print(e.custom_data)
8. 模块与包
1. 创建模块
# mymodule.py def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
# 当模块直接运行时执行的代码 if __name__ == "__main__":
print("模块测试")
print(greet("World"))
2. 导入模块
# 导入整个模块 import math
print(math.sqrt(16))
# 导入特定函数 from math import sqrt, pi
print(sqrt(16), pi)
# 导入并重命名 import numpy as np
from math import sqrt as square_root
# 导入所有 (不推荐) from math import *
3. 创建包
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
4. 常用标准库
# os - 操作系统接口 import os
os.getcwd() # 当前工作目录
os.listdir() # 列出目录内容
# sys - 系统相关参数和函数 import sys
sys.argv # 命令行参数
sys.path # Python 路径
# datetime - 日期时间处理 from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
# json - JSON 处理 import json
data = {'name': '小明', 'age': 20}
json_str = json.dumps(data) # 序列化
data2 = json.loads(json_str) # 反序列化
# re - 正则表达式 import re
pattern = r'\d+' # 匹配数字
result = re.findall(pattern, "abc123def456")
# collections - 容器数据类型 from collections import Counter, defaultdict, deque
counter = Counter(['a', 'b', 'a', 'c'])
print(counter) # Counter({'a': 2, 'b': 1, 'c': 1})
9. 高级特性
1. 迭代器与生成器
# 迭代器 class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
num = self.current
self.current -= 1
return num
for num in CountDown(5):
print(num)
# 生成器函数 def count_down(n):
while n > 0:
yield n
n -= 1
for num in count_down(5):
print(num)
# 生成器表达式 squares = (x**2 for x in range(10))
2. 装饰器
# 简单装饰器 def my_decorator(func):
def wrapper(*args, **kwargs):
print("函数执行前")
result = func(*args, **kwargs)
print("函数执行后")
return result
return wrapper
@my_decorator
def say_hello(name):
return f"Hello, {name}!"
print(say_hello("小明"))
''' 函数执行前
函数执行后
Hello, 小明! '''
# 带参数的装饰器 def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("世界")
''' Hello, 世界!
Hello, 世界!
Hello, 世界! '''


