Python备忘单 (Cheatsheet)|第九部分:附录与资源 (Appendix & Resources)
发布于 2025-09-11
分类: Python
系列文章: Python全方位教程
第 1 部分: Python语言概览|第一部分:Python入门与环境搭建 (Python Foundations)
第 2 部分: 搭建开发环境|第一部分:Python入门与环境搭建 (Python Foundations)
第 3 部分: Python基本语法与规范|第一部分:Python入门与环境搭建 (Python Foundations)
第 4 部分: 数据类型深入解析|第二部分:Python核心数据类型与运算符 (Core Data Types & Operators)
第 5 部分: 运算符大全|第二部分:Python核心数据类型与运算符 (Core Data Types & Operators)
第 6 部分: 条件与循环|第三部分:流程控制与数据结构操作 (Control Flow & Data Structures Manipulation)
第 7 部分: 数据结构高级操作|第三部分:流程控制与数据结构操作 (Control Flow & Data Structures Manipulation)
第 8 部分: 函数|第四部分:函数、模块与代码组织 (Functions, Modules & Code Organization)
第 9 部分: 模块与包|第四部分:函数、模块与代码组织 (Functions, Modules & Code Organization)
第 10 部分: 类与对象|第五部分:面向对象编程 (Object-Oriented Programming - OOP)
第 11 部分: OOP核心特性|第五部分:面向对象编程 (Object--Oriented Programming - OOP)
第 12 部分: 高级OOP主题|第五部分:面向对象编程 (Object-Oriented Programming - OOP)
第 13 部分: 迭代与生成|第六部分:高级Python编程 (Advanced Python)
第 15 部分: 内存管理与性能|第六部分:高级Python编程 (Advanced Python)
第 16 部分: 文件与目录操作|第七部分:Python标准库精选 (The Standard Library)
第 17 部分: 数据处理与序列化|第七部分:Python标准库精选 (The Standard Library)
第 18 部分: 网络与并发编程|第七部分:Python标准库精选 (The Standard Library)
第 20 部分: 系统交互|第七部分:Python标准库精选 (The Standard Library)
第 21 部分: 数据科学与分析入门|第八部分:Python生态与实战应用 (Ecosystem & Applications)
第 22 部分: Web开发入门|第八部分:Python生态与实战应用 (Ecosystem & Applications)
第 23 部分: GUI编程入门|第八部分:Python生态与实战应用 (Ecosystem & Applications)
第 24 部分: 图像处理入门|第八部分:Python生态与实战应用 (Ecosystem & Applications)
第 25 部分: 自动化脚本|第八部分:Python生态与实战应用 (Ecosystem & Applications)
第 26 部分: Python备忘单 (Cheatsheet)|第九部分:附录与资源 (Appendix & Resources) (当前)
第 27 部分: 常见面试题与解答|第九部分:附录与资源 (Appendix & Resources)
第 28 部分: 官方文档与其他学习资源链接|第九部分:附录与资源 (Appendix & Resources)
恭喜你完成了Python全方位教程的核心学习部分!你已经跋山涉水,探索了从基础语法到高级特性,从标准库到第三方生态的广阔天地。现在,为了巩固你的知识,方便你日后快速查阅,我们为你准备了这份精心制作的Python备忘单 (Cheatsheet)。
这份备忘单浓缩了Python编程中最常用、最核心的知识点。你可以把它当作你的“速查手册”,在日常编程中随时翻阅,或者在面试前快速回顾。它将是你Python工具箱中最实用的一件工具。
Python 核心备忘单
1. 基本语法与数据类型
- 变量赋值:
name = "Alice"
- 多重赋值:
x, y = 10, 20
- 注释:
# 单行注释
,"""多行注释"""
- 输入输出:
user_input = input("提示: ")
,print(f"Hello, {name}")
- 数据类型:
- 整型:
int
,100
- 浮点型:
float
,3.14
- 字符串:
str
,"Hello"
,'World'
- 布尔型:
bool
,True
,False
- 列表 (List):
[1, "a", True]
(可变) - 元组 (Tuple):
(1, "a", True)
(不可变) - 字典 (Dict):
{"key1": "value1", "key2": 2}
- 集合 (Set):
{1, "a", True}
(唯一, 无序) - 空值:
None
- 整型:
- 类型转换:
int()
,float()
,str()
,list()
,tuple()
,set()
2. 字符串操作
- 拼接:
"a" + "b"
->"ab"
- 重复:
"a" * 3
->"aaa"
- 切片:
s = "python"
,s[1:4]
->"yth"
,s[::-1]
->"nohtyp"
- 格式化 (f-string):
name = "Bob"
,f"My name is {name}"
- 常用方法:
.strip()
: 去除首尾空白.upper()
,.lower()
: 大小写转换.startswith(prefix)
,.endswith(suffix)
: 判断首尾.replace(old, new)
: 替换.split(sep)
: 分割成列表sep.join(list)
: 列表连接成字符串
3. 列表操作
- 访问:
my_list[0]
,my_list[-1]
- 添加:
my_list.append(item)
,my_list.insert(index, item)
- 删除:
my_list.pop(index)
,my_list.remove(value)
,del my_list[index]
- 排序:
my_list.sort()
(原地),new_list = sorted(my_list)
(返回新列表) - 长度:
len(my_list)
- 列表推导式:
[x*x for x in range(10) if x % 2 == 0]
4. 字典操作
- 访问:
my_dict['key']
,my_dict.get('key', default_val)
(更安全) - 增/改:
my_dict['new_key'] = 'new_value'
- 删除:
del my_dict['key']
,my_dict.pop('key')
- 遍历:
for key in my_dict.keys(): ...
for val in my_dict.values(): ...
for key, val in my_dict.items(): ...
(最常用)
5. 流程控制
- 条件判断:
if condition1: ... elif condition2: ... else: ...
- For 循环:
for item in iterable: ...
- While 循环:
while condition: ...
- 循环控制:
break
(跳出循环),continue
(跳过本次迭代) range()
:range(5)
->0,1,2,3,4
,range(1, 6, 2)
->1,3,5
6. 函数
- 定义:
def my_function(param1, param2="default"): """Docstring explaining the function.""" return param1 + param2
- 任意参数:
def func(*args, **kwargs): ...
- Lambda函数:
adder = lambda x, y: x + y
- 作用域: LEGB (Local, Enclosing, Global, Built-in),
global
,nonlocal
7. 面向对象编程 (OOP)
- 类定义:
class MyClass(ParentClass): class_attribute = "shared" def __init__(self, param1): self.instance_attribute = param1 # 实例属性 def instance_method(self): return self.instance_attribute @classmethod def class_method(cls): return cls.class_attribute @staticmethod def static_method(): return "utility function"
- 实例化:
my_obj = MyClass("value")
- 核心特性: 继承, 多态, 封装 (
_protected
,__private
) - 魔术方法:
__str__
(forprint
),__repr__
,__len__
,__add__
(for+
)
8. 文件操作
- 读写 (推荐方式):
with open("file.txt", "r", encoding="utf-8") as f: content = f.read() # or f.readline() or for line in f: with open("file.txt", "w", encoding="utf-8") as f: f.write("some text")
- 模式:
'r'
(读),'w'
(写),'a'
(追加),'b'
(二进制)
9. 异常处理
try:
# code that might raise an exception
risky_operation()
except ValueError as e:
# handle specific exception
print(f"Invalid value: {e}")
except Exception as e:
# handle any other exception
print(f"An error occurred: {e}")
else:
# if no exception was raised
print("Operation successful.")
finally:
# always executed, for cleanup
print("Execution finished.")
10. 常用模块
os
:os.getcwd()
,os.path.join()
,os.listdir()
,os.mkdir()
sys
:sys.argv
,sys.platform
,sys.exit()
datetime
:datetime.now()
,timedelta
,strftime()
,strptime()
math
:math.sqrt()
,math.sin()
,math.pi
random
:random.randint(a, b)
,random.choice(list)
,random.shuffle(list)
json
:json.dumps(obj)
,json.loads(str)
,json.dump()
,json.load()
requests
(第三方):requests.get(url)
,requests.post(url, data=payload)
这份备忘单是你知识体系的骨架。请将它保存在一个方便查找的地方。当你遇到问题时,先尝试在这里寻找线索,这将极大地锻炼你独立解决问题的能力。
在下一章,也是我们教程的最后一章,我们将为你精选一些常见的Python面试题,并提供学习资源的链接,助你在求职和持续学习的道路上走得更远。准备好,为你的Python之旅画上一个完美的句号,并开启新的征程!