外观
Python 笔记
约 3736 字大约 12 分钟
2025-08-16
一、Python 简介
1.1 什么是 Python?
Python 是一种高级、解释型、通用编程语言,具有以下特点:
- 简洁易读:语法清晰,接近自然语言
- 跨平台:支持 Windows、Linux、Mac 等多种操作系统
- 解释型语言:无需编译,直接运行
- 动态类型:变量类型在运行时确定
- 丰富的标准库:内置大量实用模块
- 广泛应用:Web 开发、数据分析、人工智能、自动化脚本等
1.2 Python 2 vs Python 3
目前主流使用 Python 3(推荐 3.6+),Python 2 已于 2020 年停止支持。主要区别:
print从语句变为函数:print("Hello")而非print "Hello"- 整数除法:
5 / 2 = 2.5(Python 3)vs5 / 2 = 2(Python 2) - Unicode 支持更好:Python 3 中字符串默认为 Unicode
二、Python 基础语法
2.1 注释
# 这是单行注释
"""
这是多行注释
可以跨越多行
"""
'''
这也是多行注释
效果与上面相同
'''2.2 变量和常量
变量命名规则:
- 由字母、数字、下划线组成,不能以数字开头
- 区分大小写(
myVar和myvar是不同的变量) - 不能使用 Python 关键字(如
if,for,class等) - 推荐使用小写字母和下划线(
snake_case风格)
# 变量定义与赋值
name = "Python" # 字符串
age = 30 # 整数
price = 9.99 # 浮点数
is_active = True # 布尔值
# 多变量赋值
a = b = c = 1 # 三个变量都赋值为1
x, y, z = 1, 2, "A" # 分别赋值
# 常量(Python 没有真正的常量,约定使用全大写)
MAX_CONNECTIONS = 1002.3 缩进与代码块
Python 使用缩进(通常为 4 个空格)来表示代码块,不使用大括号:
if True:
print("Hello") # 缩进表示这个语句属于 if 块
print("World") # 同一个代码块
else:
print("Goodbye") # else 块注意:缩进不一致会导致语法错误!
2.4 输入与输出
# 输出
print("Hello World") # 基本输出
print("Name:", name) # 多个值输出,自动添加空格
print("Price:", price, sep="|") # 自定义分隔符
print("No newline", end=" ") # 不换行
# 输入
user_input = input("Enter something: ")
print("You entered:", user_input)三、数据类型
3.1 数字类型
| 类型 | 描述 | 示例 |
|---|---|---|
int | 整数 | 42, -7, 0 |
float | 浮点数 | 3.14, -0.001, 2.0 |
complex | 复数 | 1+2j, 3j |
# 基本运算
a = 10
b = 3
print(a + b) # 13 (加法)
print(a - b) # 7 (减法)
print(a * b) # 30 (乘法)
print(a / b) # 3.333... (除法,结果为float)
print(a // b) # 3 (整除)
print(a % b) # 1 (取模)
print(a ** b) # 1000 (幂运算)
# 类型转换
int_value = int(3.9) # 3
float_value = float(5) # 5.03.2 字符串
字符串创建:
s1 = '单引号字符串'
s2 = "双引号字符串"
s3 = """多行
字符串"""
s4 = '''也可以
这样写'''常用操作:
text = "Hello, Python"
# 索引和切片
print(text[0]) # H (第一个字符)
print(text[-1]) # n (最后一个字符)
print(text[0:5]) # Hello (切片)
print(text[7:]) # Python (从索引7到结束)
print(text[:5]) # Hello (从开始到索引5)
print(text[::2]) # Hlo yhn (步长为2)
# 常用方法
print(len(text)) # 13 (长度)
print(text.upper()) # HELLO, PYTHON (转大写)
print(text.lower()) # hello, python (转小写)
print(text.replace("Python", "World")) # Hello, World
print(text.split(",")) # ['Hello', ' Python'] (分割)
print(" trim ".strip()) # trim (去除空白)
print("Python" in text) # True (成员检查)
# 格式化
name = "Alice"
age = 30
# f-string (Python 3.6+ 推荐)
print(f"My name is {name} and I'm {age} years old.")
# format() 方法
print("My name is {} and I'm {} years old.".format(name, age))
# % 格式化 (较旧方式)
print("My name is %s and I'm %d years old." % (name, age))3.3 列表(List)
列表特点:
- 有序、可变、允许重复元素
- 使用方括号
[]定义 - 可包含不同类型的元素
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# 常用操作
print(len(fruits)) # 3 (长度)
print(fruits[0]) # apple (索引)
print(fruits[-1]) # cherry (负索引)
print(fruits[1:3]) # ['banana', 'cherry'] (切片)
# 修改列表
fruits[1] = "blueberry" # 修改元素
fruits.append("orange") # 添加元素到末尾
fruits.insert(1, "mango") # 在指定位置插入
fruits.remove("cherry") # 移除指定元素
popped = fruits.pop() # 移除并返回最后一个元素
fruits.clear() # 清空列表
# 列表操作
nums = [3, 1, 4, 2]
nums.sort() # 排序 [1, 2, 3, 4]
nums.reverse() # 反转 [4, 3, 2, 1]
combined = fruits + nums # 合并列表
repeated = nums * 2 # 重复列表
# 列表推导式 (强大且常用)
squares = [x * x for x in range(10)]
even_squares = [x * x for x in range(10) if x % 2 == 0]3.4 元组(Tuple)
元组特点:
- 有序、不可变、允许重复元素
- 使用圆括号
()定义 - 比列表更轻量,适合不需要修改的数据
# 创建元组
colors = ("red", "green", "blue")
single = (42,) # 单个元素的元组需要逗号
# 访问元素
print(colors[0]) # red
print(colors[1:3]) # ('green', 'blue')
# 元组解包
r, g, b = colors
print(r, g, b) # red green blue
# 元组操作
print(len(colors)) # 3
print("red" in colors) # True
# 元组不可修改
# colors[0] = "yellow" # 会报错!3.5 字典(Dictionary)
字典特点:
- 无序、可变、键值对存储
- 键必须是不可变类型(字符串、数字、元组)
- 键必须唯一
- 使用花括号
{}或dict()创建
# 创建字典
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 或者
person = dict(name="Alice", age=30, city="New York")
# 访问元素
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("country", "USA")) # USA (默认值)
# 修改字典
person["age"] = 31 # 修改值
person["email"] = "alice@example.com" # 添加新键值对
person.update({"city": "Boston", "job": "Developer"}) # 批量更新
# 删除元素
del person["email"]
removed = person.pop("job") # 移除并返回值
person.clear() # 清空字典
# 字典操作
print(len(person)) # 3
print("name" in person) # True
# 遍历字典
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
# 字典推导式
squares = {x: x*x for x in range(5)}3.6 集合(Set)
集合特点:
- 无序、不重复
- 支持数学集合操作(并集、交集等)
- 使用花括号
{}或set()创建 - 注意:空集合必须用
set(),{}是空字典
# 创建集合
fruits = {"apple", "banana", "cherry"}
nums = set([1, 2, 3, 2, 1]) # {1, 2, 3} (自动去重)
# 常用操作
fruits.add("orange") # 添加元素
fruits.remove("banana") # 移除元素(不存在会报错)
fruits.discard("grape") # 移除元素(不存在不会报错)
popped = fruits.pop() # 随机移除并返回一个元素
# 集合操作
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5} (并集)
print(a & b) # {3} (交集)
print(a - b) # {1, 2} (差集)
print(a ^ b) # {1, 2, 4, 5} (对称差集)
# 集合推导式
squares = {x*x for x in range(5)} # {0, 1, 4, 9, 16}四、运算符
4.1 算术运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
+ | 加法 | 3 + 2 = 5 |
- | 减法 | 3 - 2 = 1 |
* | 乘法 | 3 * 2 = 6 |
/ | 除法 | 3 / 2 = 1.5 |
// | 整除 | 3 // 2 = 1 |
% | 取模 | 3 % 2 = 1 |
** | 幂运算 | 3 ** 2 = 9 |
4.2 比较运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
== | 等于 | 3 == 2 返回 False |
!= | 不等于 | 3 != 2 返回 True |
> | 大于 | 3 > 2 返回 True |
< | 小于 | 3 < 2 返回 False |
>= | 大于等于 | 3 >= 2 返回 True |
<= | 小于等于 | 3 <= 2 返回 False |
4.3 逻辑运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
and | 与 | True and False 返回 False |
or | 或 | True or False 返回 True |
not | 非 | not True 返回 False |
4.4 赋值运算符
| 运算符 | 描述 | 示例 | 等效于 |
|---|---|---|---|
= | 简单赋值 | x = 5 | - |
+= | 加后赋值 | x += 3 | x = x + 3 |
-= | 减后赋值 | x -= 3 | x = x - 3 |
*= | 乘后赋值 | x *= 3 | x = x * 3 |
/= | 除后赋值 | x /= 3 | x = x / 3 |
//= | 整除后赋值 | x //= 3 | x = x // 3 |
%= | 取模后赋值 | x %= 3 | x = x % 3 |
**= | 幂后赋值 | x **= 3 | x = x ** 3 |
4.5 成员运算符
| 运算符 | 描述 | 示例 |
|---|---|---|
in | 如果在指定序列中找到值返回 True | "a" in "abc" 返回 True |
not in | 如果在指定序列中没有找到值返回 True | "d" not in "abc" 返回 True |
五、流程控制
5.1 条件语句
age = 20
# if 语句
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# 多条件判断
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"Your grade is {grade}")
# 三元表达式
status = "adult" if age >= 18 else "minor"
print(f"You are {status}")5.2 循环语句
for 循环:
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字符串
for char in "Python":
print(char)
# 遍历范围
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# 带索引遍历
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 遍历字典
person = {"name": "Alice", "age": 30}
for key, value in person.items():
print(f"{key}: {value}")while 循环:
count = 0
while count < 5:
print(count)
count += 1
# 带条件的循环
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
# break 和 continue
for i in range(10):
if i == 3:
continue # 跳过本次循环
if i == 7:
break # 终止整个循环
print(i) # 输出 0,1,2,4,5,65.3 异常处理
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"10 / {num} = {result}")
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("Operation completed successfully!")
finally:
print("This will always execute")六、函数
6.1 定义与调用
# 定义函数
def greet(name):
"""这是一个问候函数"""
print(f"Hello, {name}!")
# 调用函数
greet("Alice") # 输出: Hello, Alice!
# 带返回值的函数
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 86.2 参数类型
位置参数:
def greet(name, message):
print(f"{message}, {name}!")
greet("Alice", "Hello") # Hello, Alice!关键字参数:
greet(message="Hi", name="Bob") # Hi, Bob!默认参数:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Goodbye") # Goodbye, Bob!可变位置参数:
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3, 4)) # 10可变关键字参数:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
# name: Alice
# age: 30
# city: New York强制位置参数(Python 3.8+):
def f(a, b, /, c, d, *, e, f):
"""a, b 必须是位置参数,c, d 可以是位置或关键字参数,e, f 必须是关键字参数"""
print(a, b, c, d, e, f)
f(1, 2, 3, d=4, e=5, f=6) # 正确
# f(1, 2, 3, 4, e=5, f=6) # 也正确
# f(1, 2, c=3, d=4, e=5, f=6) # 错误,c 不能是关键字参数6.3 Lambda 表达式
# 简单的 lambda 函数
double = lambda x: x * 2
print(double(5)) # 10
# 在排序中使用
points = [(1, 2), (3, 1), (5, 0)]
points_sorted = sorted(points, key=lambda x: x[1])
print(points_sorted) # [(5, 0), (3, 1), (1, 2)]
# 在 filter 和 map 中使用
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
squared = list(map(lambda x: x * x, numbers))七、面向对象编程
7.1 类与对象
# 定义类
class Person:
# 类变量(所有实例共享)
species = "Homo sapiens"
# 构造方法
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name} and I'm {self.age} years old."
# 类方法(使用 @classmethod 装饰器)
@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2023 - birth_year)
# 静态方法(使用 @staticmethod 装饰器)
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person1 = Person("Alice", 30)
person2 = Person.from_birth_year("Bob", 1990)
# 访问属性和方法
print(person1.name) # Alice
print(person1.greet()) # Hello, my name is Alice and I'm 30 years old.
print(Person.species) # Homo sapiens
print(Person.is_adult(20)) # True7.2 继承
# 基类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# 派生类
class Dog(Animal):
def __init__(self, name, breed):
# 调用父类构造方法
super().__init__(name)
self.breed = breed
# 重写方法
def speak(self):
return "Woof!"
# 使用
dog = Dog("Buddy", "Golden Retriever")
print(dog.name) # Buddy
print(dog.breed) # Golden Retriever
print(dog.speak()) # Woof!
# isinstance 和 issubclass
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True7.3 封装与属性
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
# 私有属性(约定使用单下划线)
self._balance = balance
# 公共方法
def deposit(self, amount):
if amount > 0:
self._balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
return True
return False
# 属性(使用@property装饰器)
@property
def balance(self):
return self._balance
# 可设置的属性
@balance.setter
def balance(self, value):
if value >= 0:
self._balance = value
# 使用
account = BankAccount("Alice", 1000)
print(account.balance) # 1000
account.deposit(500)
print(account.balance) # 1500
account.withdraw(200)
print(account.balance) # 1300
account.balance = 2000 # 通过setter设置八、文件操作
8.1 读写文本文件
# 写入文件(覆盖模式)
with open("example.txt", "w") as file:
file.write("Hello\n")
file.write("World\n")
# 写入文件(追加模式)
with open("example.txt", "a") as file:
file.write("Appended text\n")
# 读取整个文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 逐行读取
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() 移除换行符
# 读取所有行到列表
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)8.2 读写 JSON 文件
import json
# 写入 JSON
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
# 读取 JSON
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data["name"]) # Alice8.3 读写 CSV 文件
import csv
# 写入 CSV
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Boston"]
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
# 读取 CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)九、常用模块
9.1 datetime - 日期和时间处理
from datetime import datetime, timedelta
# 获取当前时间
now = datetime.now()
print(now) # 2023-08-15 14:30:00.123456
# 格式化时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) # 2023-08-15 14:30:00
# 解析字符串
date_str = "2023-08-15"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
# 时间计算
tomorrow = now + timedelta(days=1)
one_hour_ago = now - timedelta(hours=1)9.2 os - 操作系统接口
import os
# 获取当前工作目录
print(os.getcwd())
# 列出目录内容
print(os.listdir("."))
# 创建目录
os.makedirs("new_folder", exist_ok=True)
# 路径操作
path = os.path.join("folder", "subfolder", "file.txt")
print(path) # folder/subfolder/file.txt
# 检查路径
print(os.path.exists("example.txt"))
print(os.path.isfile("example.txt"))
print(os.path.isdir("folder"))9.3 sys - 系统相关参数和函数
import sys
# 命令行参数
print(sys.argv) # 第一个元素是脚本名称
# Python 版本
print(sys.version)
# 平台信息
print(sys.platform) # 'win32', 'linux', 'darwin' 等
# 标准输入输出
sys.stdout.write("Hello\n")
input_data = sys.stdin.readline()十、最佳实践
10.1 代码风格
- 遵循 PEP 8 代码风格指南
- 使用 4 个空格缩进(不要用 Tab)
- 每行不超过 79 个字符
- 函数和类之间用两个空行分隔
- 导入语句分组:标准库、第三方库、本地应用
- 使用有意义的变量和函数名
- 为函数和类添加文档字符串
# 好的命名
def calculate_average(numbers):
"""计算数字列表的平均值
Args:
numbers: 数字列表
Returns:
平均值,如果列表为空则返回0
"""
if not numbers:
return 0
return sum(numbers) / len(numbers)10.2 虚拟环境
使用虚拟环境隔离项目依赖:
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows: venv\Scripts\activate
# macOS/Linux: source venv/bin/activate
# 安装依赖
pip install requests pandas
# 生成依赖文件
pip freeze > requirements.txt
# 从依赖文件安装
pip install -r requirements.txt10.3 异常处理原则
- 不要捕获过于宽泛的异常(避免
except:) - 明确指定要捕获的异常类型
- 不要忽略捕获的异常(至少记录日志)
- 使用
finally确保资源释放 - 对于可恢复的错误,提供明确的错误信息
try:
# 可能出错的代码
result = 10 / int(user_input)
except ValueError:
print("请输入有效的数字")
except ZeroDivisionError:
print("不能除以零")
else:
print(f"结果是: {result}")
finally:
print("操作完成")10.4 列表推导式 vs 循环
列表推导式更简洁、高效,但仅适用于简单操作:
# 使用列表推导式(推荐)
squares = [x * x for x in range(10)]
# 使用循环(更复杂的情况)
squares = []
for x in range(10):
if x % 2 == 0:
squares.append(x * x)
# 字典推导式
square_dict = {x: x * x for x in range(5)}
# 生成器表达式(节省内存)
square_gen = (x * x for x in range(10))