Python 核心语法与基础数据结构指南
一、 代码注释规范
在 Python 中,注释用于解释代码逻辑,解释器在执行时会忽略这些内容。良好的注释习惯能显著提升代码的可读性和可维护性。
1. 单行注释
使用井号 # 开头的单行注释,通常用于解释紧随其后的单行代码。
# 计算用户的最终折扣价格
final_price = original_price * discount_rate
2. 多行注释与文档字符串
Python 没有严格意义上的多行注释语法,通常使用三个单引号 ''' 或三个双引号 """ 包裹多行文本。当这种多行字符串出现在模块、类或函数的开头时,它被称为文档字符串(Docstring),可被 help() 函数或 IDE 解析。
"""
这是一个多行文本块。
通常用于编写模块说明或函数的 Docstring。
解释器不会将其作为常规代码执行。
"""
def calculate_area(radius):
"""
计算圆的面积。
:param radius: 圆的半径
:return: 圆的面积
"""
return 3.14159 * radius ** 2
二、 标准输入与输出
1. 控制台输入
使用 input() 函数从标准输入读取一行数据,返回值始终为字符串类型。
user_name = input("请输入您的用户名: ")
print(f"欢迎, {user_name}!")
2. 控制台输出
print() 函数用于将数据输出到标准输出设备。在现代 Python 开发中,推荐使用 f-string(格式化字符串字面值)进行变量插值。
item_name = "机械键盘"
price = 499.50
quantity = 2
# 直接输出与多变量输出
print("订单明细:")
print(item_name, price, quantity)
# 使用 f-string 进行格式化输出
total_cost = price * quantity
print(f"商品: {item_name}, 总价: {total_cost:.2f} 元")
三、 核心数据类型
Python 是动态类型语言,变量无需显式声明类型。内置数据类型主要分为数值、序列、映射和集合。
1. 数值类型 (Int, Float, Bool)
- Int (整型):支持任意精度的整数。
- Float (浮点型):双精度浮点数,支持科学计数法。
- Bool (布尔型):仅有
True和False两个值,本质上是1和0的子类。
max_connections = 1000 # int
timeout_seconds = 30.5 # float
is_server_running = True # bool
# 类型转换与数学运算
print(int("42")) # 字符串转整型
print(float(10)) # 整型转浮点型
print(10 // 3) # 整除,结果为 3
print(10 % 3) # 取余,结果为 1
print(2 ** 8) # 幂运算,结果为 256
2. 字符串 (Str)
字符串是不可变的字符序列,支持单引号、双引号和三引号定义。Python 提供了丰富的字符串处理方法。
log_message = " Error: Connection Timeout! "
# 去除两端空白并转换为小写
clean_message = log_message.strip().lower()
print(clean_message) # 输出: error: connection timeout!
# 字符串分割与拼接
csv_data = "apple,banana,cherry"
fruits_list = csv_data.split(",")
rejoined_data = " | ".join(fruits_list)
print(rejoined_data) # 输出: apple | banana | cherry
# 查找与替换
print(clean_message.find("timeout")) # 返回子串起始索引
print(clean_message.replace("error", "warning"))
3. 空值 (None)
None 是 NoneType 的唯一实例,表示空值或缺失值,常用于函数没有显式返回值时的默认返回。
4. 列表 (List) 与 元组 (Tuple)
列表是有序且可变的集合,使用方括号 [] 定义;元组是有序且不可变的集合,使用圆括号 () 定义。
# 列表操作
server_ports = [80, 443, 8080]
server_ports.append(8443) # 末尾添加
server_ports.insert(0, 22) # 指定位置插入
server_ports.remove(8080) # 移除特定值
print(server_ports) # [22, 80, 443, 8443]
# 元组操作 (常用于表示不可变的数据结构,如坐标、数据库记录)
db_config = ("localhost", 5432, "postgres")
host, port, user = db_config # 元组解包
print(f"Connecting to {host}:{port} as {user}")
5. 字典 (Dict)
字典是键值对的无序集合(Python 3.7+ 保证插入顺序),键必须是可哈希的不可变类型。
user_session = {
"user_id": 1024,
"username": "dev_ops",
"is_authenticated": True
}
# 访问与修改
print(user_session.get("username")) # 安全获取,不存在返回 None
user_session["last_login"] = "2023-10-25"
# 遍历字典
for key, value in user_session.items():
print(f"{key}: {value}")
6. 集合 (Set)
集合是无序且不包含重复元素的容器,底层基于哈希表实现,常用于去重和集合运算。
active_users = {"alice", "bob", "charlie"}
premium_users = {"charlie", "david", "eve"}
# 集合运算
print(active_users & premium_users) # 交集: {'charlie'}
print(active_users | premium_users) # 并集: {'alice', 'bob', 'charlie', 'david', 'eve'}
print(active_users - premium_users) # 差集: {'alice', 'bob'}
7. 可变与不可变对象
理解内存模型对于避免隐蔽的 Bug 至关重要。
- 不可变类型:Int, Float, Bool, Str, Tuple。修改其值实际上是创建了一个新对象并重新绑定引用。
- 可变类型:List, Dict, Set。可以在原内存地址上直接修改其内容。
四、 控制流:条件与循环
1. 条件分支
使用 if, elif, else 构建条件逻辑,结合 and, or, not 进行布尔运算。
cpu_usage = 85
memory_usage = 60
if cpu_usage > 90 or memory_usage > 90:
status = "CRITICAL"
elif cpu_usage > 70 and memory_usage > 70:
status = "WARNING"
else:
status = "NORMAL"
print(f"System Status: {status}")
2. 循环结构
for 循环用于遍历可迭代对象,while 循环用于条件驱动的重复执行。
# for 循环与 enumerate
log_files = ["app.log", "error.log", "access.log"]
for index, file_name in enumerate(log_files):
print(f"[{index}] Processing {file_name}...")
# while 循环与 break/continue
retry_count = 0
max_retries = 3
while retry_count < max_retries:
success = attempt_connection()
if success:
print("Connected successfully.")
break
retry_count += 1
if retry_count == max_retries:
print("Max retries reached. Aborting.")
五、 函数与作用域
函数通过 def 关键字定义,支持位置参数、关键字参数、默认参数以及可变参数。
def process_data(data_source, batch_size=100, *filters, **options):
"""处理数据流的通用函数"""
print(f"Source: {data_source}, Batch: {batch_size}")
print(f"Applied filters: {filters}")
print(f"Extra options: {options}")
# 调用函数
process_data(
"kafka_topic_A",
500,
"drop_nulls", "normalize",
timeout=30, retry=True
)
作用域规则 (LEGB):Python 变量查找顺序为 Local (局部) -> Enclosing (嵌套) -> Global (全局) -> Built-in (内置)。若需在函数内修改全局变量,需使用 global 关键字声明。
六、 模块与包管理
模块是包含 Python 代码的 .py 文件。通过 import 机制实现代码复用和命名空间隔离。
# 导入整个模块
import math
print(math.sqrt(16))
# 导入特定函数并重命名
from datetime import datetime as dt
current_time = dt.now()
# 导入自定义模块
from utils.data_parser import parse_json
七、 日期与时间处理
Python 提供了 time、datetime 和 calendar 模块来处理时间相关任务。现代开发中,推荐使用 datetime 模块。
import time
from datetime import datetime, timedelta
# 获取当前时间戳
timestamp = time.time()
# datetime 对象操作
now = datetime.now()
future_date = now + timedelta(days=7, hours=3)
# 格式化与解析
formatted_str = future_date.strftime("%Y-%m-%d %H:%M:%S")
parsed_date = datetime.strptime("2023-11-01 12:00:00", "%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted_str}")
print(f"Parsed: {parsed_date}")
八、 文件 I/O 与操作系统交互
进行文件操作时,强烈建议使用 with 语句(上下文管理器),它能确保文件在使用完毕后自动关闭,即使发生异常也能正确释放资源。
1. 文件读写
# 写入文件
with open("config.yaml", "w", encoding="utf-8") as file:
file.write("server:\n host: 0.0.0.0\n port: 8080\n")
# 读取文件
with open("config.yaml", "r", encoding="utf-8") as file:
for line_number, line in enumerate(file, 1):
print(f"Line {line_number}: {line.strip()}")
2. 文件指针与截断
with open("data.bin", "rb+") as file:
file.seek(10) # 移动指针到第 10 个字节
position = file.tell() # 获取当前指针位置
file.truncate(50) # 截断文件,保留前 50 个字节
3. 目录与路径操作 (pathlib)
相较于传统的 os.path,pathlib 提供了面向对象的现代路径操作方式。
from pathlib import Path
log_dir = Path("/var/log/myapp")
log_dir.mkdir(parents=True, exist_ok=True)
# 遍历目录下的所有 .log 文件
for log_file in log_dir.glob("*.log"):
print(f"Found log: {log_file.name}, Size: {log_file.stat().st_size} bytes")
九、 异常处理机制
Python 使用 try-except-else-finally 结构来捕获和处理运行时异常,保证程序的健壮性。
1. 捕获与处理异常
def read_config(file_path):
try:
with open(file_path, "r") as f:
return f.read()
except FileNotFoundError as e:
print(f"Error: Configuration file missing. ({e})")
return None
except PermissionError:
print("Error: Insufficient permissions to read the file.")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
raise # 重新抛出未预期的异常
else:
print("Configuration loaded successfully.")
finally:
print("Execution of config reader completed.")
2. 自定义异常
通过继承 Exception 基类,可以创建符合业务逻辑的自定义异常。
class InsufficientFundsError(Exception):
"""余额不足异常"""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}. Current balance: {balance}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
new_balance = withdraw(100, 150)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")