Python 快速参考手册
🚀 基础语法
变量和数据类型
# 基本数据类型
name = "Python" # 字符串 (str)
age = 30 # 整数 (int)
height = 5.9 # 浮点数 (float)
is_student = True # 布尔值 (bool)
data = None # 空值 (NoneType)
# 类型检查
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
字符串操作
# 字符串基础
text = "Hello, World!"
print(len(text)) # 13
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.replace("World", "Python")) # Hello, Python!
# 字符串格式化
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
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))
运算符
# 算术运算符
a, b = 10, 3
print(a + b) # 13 (加法)
print(a - b) # 7 (减法)
print(a * b) # 30 (乘法)
print(a / b) # 3.333... (除法)
print(a // b) # 3 (整除)
print(a % b) # 1 (取余)
print(a ** b) # 1000 (幂运算)
# 比较运算符
print(a > b) # True
print(a == b) # False
print(a != b) # True
# 逻辑运算符
print(True and False) # False
print(True or False) # True
print(not True) # False
🔄 控制流
条件语句
# if-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
# 三元运算符
result = "Pass" if score >= 60 else "Fail"
循环
# for 循环
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for char in "Python":
print(char) # P, y, t, h, o, n
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 循环控制
for i in range(10):
if i == 3:
continue # 跳过当前迭代
if i == 7:
break # 退出循环
print(i)
📊 数据结构
列表 (List)
# 创建和操作
fruits = ["apple", "banana", "orange"]
fruits.append("grape") # 添加元素
fruits.insert(1, "kiwi") # 插入元素
fruits.remove("banana") # 删除元素
popped = fruits.pop() # 弹出最后一个元素
# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 常用方法
print(len(fruits)) # 长度
print(fruits.index("apple")) # 查找索引
print(fruits.count("apple")) # 计数
fruits.sort() # 排序
fruits.reverse() # 反转
字典 (Dictionary)
# 创建和操作
person = {"name": "Alice", "age": 30, "city": "New York"}
person["email"] = "alice@example.com" # 添加键值对
del person["city"] # 删除键值对
# 字典方法
print(person.keys()) # 获取所有键
print(person.values()) # 获取所有值
print(person.items()) # 获取所有键值对
print(person.get("phone", "N/A")) # 安全获取值
# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
元组 (Tuple)
# 创建(不可变)
coordinates = (10, 20)
rgb = (255, 128, 0)
# 元组解包
x, y = coordinates
r, g, b = rgb
# 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)
集合 (Set)
# 创建和操作
numbers = {1, 2, 3, 4, 5}
numbers.add(6) # 添加元素
numbers.remove(3) # 删除元素
numbers.discard(10) # 安全删除(不存在不报错)
# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2) # 交集 {3, 4}
print(set1 | set2) # 并集 {1, 2, 3, 4, 5, 6}
print(set1 - set2) # 差集 {1, 2}
🔧 函数
函数定义
# 基本函数
def greet(name):
"""问候函数"""
return f"Hello, {name}!"
# 默认参数
def power(base, exponent=2):
return base ** exponent
# 可变参数
def sum_all(*args):
return sum(args)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# 函数调用
print(greet("Alice"))
print(power(3)) # 使用默认参数
print(power(3, 4)) # 指定参数
print(sum_all(1, 2, 3, 4, 5))
print_info(name="Bob", age=25, city="Paris")
Lambda 函数
# 匿名函数
square = lambda x: x**2
add = lambda x, y: x + y
# 与内置函数结合使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
🏗️ 面向对象编程
类和对象
class Person:
# 类属性
species = "Homo sapiens"
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age
def introduce(self):
# 实例方法
return f"Hi, I'm {self.name} and I'm {self.age} years old"
@classmethod
def from_birth_year(cls, name, birth_year):
# 类方法
age = 2024 - birth_year
return cls(name, age)
@staticmethod
def is_adult(age):
# 静态方法
return age >= 18
# 使用类
person1 = Person("Alice", 30)
person2 = Person.from_birth_year("Bob", 1990)
print(person1.introduce())
print(Person.is_adult(16))
继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# 多态
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())
特殊方法
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"Book: {self.title}"
def __repr__(self):
return f"Book('{self.title}', {self.pages})"
def __len__(self):
return self.pages
def __eq__(self, other):
return self.title == other.title
def __lt__(self, other):
return self.pages < other.pages
book = Book("Python Guide", 300)
print(str(book)) # Book: Python Guide
print(len(book)) # 300
🔄 高级特性
装饰器
# 简单装饰器
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
return "Done"
# 带参数的装饰器
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 say_hello():
print("Hello!")
生成器
# 生成器函数
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)
# 生成器表达式
squares = (x**2 for x in range(10))
print(list(squares))
上下文管理器
# 使用 with 语句
with open('file.txt', 'r') as f:
content = f.read()
# 文件自动关闭
# 自定义上下文管理器
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
self.end = time.time()
print(f"Elapsed time: {self.end - self.start:.4f} seconds")
with Timer():
# 一些耗时操作
sum(range(1000000))
📁 文件操作
文件读写
# 写文件
with open('data.txt', 'w') as f:
f.write("Hello, World!\n")
f.writelines(["Line 1\n", "Line 2\n"])
# 读文件
with open('data.txt', 'r') as f:
content = f.read() # 读取全部内容
with open('data.txt', 'r') as f:
lines = f.readlines() # 读取所有行
with open('data.txt', 'r') as f:
for line in f: # 逐行读取
print(line.strip())
# JSON 操作
import json
data = {"name": "Alice", "age": 30}
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
with open('data.json', 'r') as f:
loaded_data = json.load(f)
⚠️ 异常处理
基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No exceptions occurred")
finally:
print("This always executes")
# 抛出异常
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
📦 模块和包
导入模块
# 标准库
import os
import sys
from datetime import datetime, date
from collections import defaultdict, Counter
# 第三方库
import requests
import numpy as np
import pandas as pd
# 自定义模块
from my_module import my_function
from my_package.my_module import MyClass
创建模块
# my_utils.py
def add(a, b):
"""加法函数"""
return a + b
def multiply(a, b):
"""乘法函数"""
return a * b
PI = 3.14159
# 使用模块
import my_utils
result = my_utils.add(5, 3)
🧪 测试
单元测试
import unittest
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
def test_divide(self):
self.assertEqual(divide(10, 2), 5)
with self.assertRaises(ZeroDivisionError):
divide(10, 0)
def setUp(self):
# 测试前准备
self.test_data = [1, 2, 3, 4, 5]
def tearDown(self):
# 测试后清理
pass
if __name__ == '__main__':
unittest.main()
🔍 常用内置函数
# 数学函数
abs(-5) # 5 (绝对值)
max(1, 2, 3) # 3 (最大值)
min(1, 2, 3) # 1 (最小值)
sum([1, 2, 3]) # 6 (求和)
round(3.14159, 2) # 3.14 (四舍五入)
# 类型转换
int("123") # 123
float("3.14") # 3.14
str(123) # "123"
list("hello") # ['h', 'e', 'l', 'l', 'o']
tuple([1, 2, 3]) # (1, 2, 3)
# 序列函数
len([1, 2, 3]) # 3 (长度)
sorted([3, 1, 2]) # [1, 2, 3] (排序)
reversed([1, 2, 3]) # 反向迭代器
enumerate(['a', 'b']) # [(0, 'a'), (1, 'b')]
zip([1, 2], ['a', 'b']) # [(1, 'a'), (2, 'b')]
# 过滤和映射
filter(lambda x: x > 0, [-1, 0, 1, 2]) # [1, 2]
map(lambda x: x**2, [1, 2, 3]) # [1, 4, 9]
all([True, True, False]) # False
any([True, False, False]) # True
📚 常用标准库
# 日期时间
from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)
# 随机数
import random
random.randint(1, 10) # 1-10之间的随机整数
random.choice(['a', 'b', 'c']) # 随机选择
random.shuffle([1, 2, 3]) # 随机打乱
# 正则表达式
import re
pattern = r'\d+' # 匹配数字
text = "I have 5 apples and 3 oranges"
numbers = re.findall(pattern, text) # ['5', '3']
# 系统操作
import os
os.getcwd() # 获取当前目录
os.listdir('.') # 列出目录内容
os.path.exists('file.txt') # 检查文件是否存在
# HTTP 请求
import requests
response = requests.get('https://api.github.com')
data = response.json()
🎯 最佳实践
代码风格 (PEP 8)
# 好的命名
user_name = "alice" # 变量用下划线
MAX_SIZE = 100 # 常量用大写
class UserAccount: # 类名用驼峰命名
pass
def calculate_total(): # 函数名用下划线
pass
# 适当的空格和换行
def function(param1, param2):
"""函数文档字符串"""
if param1 > param2:
return param1
else:
return param2
# 导入顺序
import os # 标准库
import sys
import requests # 第三方库
from my_module import func # 本地模块
错误处理
# 具体的异常处理
try:
with open('file.txt', 'r') as f:
data = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
except Exception as e:
print(f"Unexpected error: {e}")
性能优化
# 使用列表推导式而不是循环
# 慢
result = []
for i in range(1000):
if i % 2 == 0:
result.append(i**2)
# 快
result = [i**2 for i in range(1000) if i % 2 == 0]
# 使用生成器节省内存
def large_sequence():
for i in range(1000000):
yield i**2
# 使用 join 连接字符串
# 慢
result = ""
for word in words:
result += word + " "
# 快
result = " ".join(words)
这个快速参考手册涵盖了 Python 编程的核心概念和常用语法。建议收藏并在编程时随时查阅!🐍✨
