引言:为什么选择Python作为你的编程起点

Python作为当今最流行的编程语言之一,以其简洁的语法、强大的生态系统和广泛的应用场景,成为零基础学习者的首选。根据2023年Stack Overflow开发者调查,Python连续多年位居最受欢迎编程语言前三名。对于初学者来说,Python的可读性极强,几乎像读英语一样容易理解,这大大降低了学习门槛。

Python的应用领域极其广泛:

  • Web开发:Django、Flask等框架让网站开发变得高效
  • 数据分析:Pandas、NumPy、Matplotlib等库让数据处理可视化变得简单
  • 人工智能/机器学习:TensorFlow、PyTorch等框架让AI开发触手可及
  • 自动化脚本:从文件操作到网络爬虫,Python都能胜任
  • 游戏开发:Pygame等库让游戏开发变得有趣

第一阶段:搭建Python学习环境(第1-2周)

1.1 Python版本选择与安装

对于初学者,我强烈推荐安装Python 3.x版本。Python 2.x已于2020年正式停止维护,因此新项目都应该使用Python 3。

Windows系统安装步骤:

  1. 访问Python官网 https://www.python.org/downloads/
  2. 点击”Download Python 3.x.x”按钮
  3. 运行安装程序,务必勾选”Add Python to PATH”选项
  4. 点击”Install Now”完成安装

macOS系统安装步骤:

  1. 推荐使用Homebrew安装:brew install python3
  2. 或者从官网下载安装包

Linux系统安装步骤:

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

# CentOS/RHEL
sudo yum install python3 python3-pip

1.2 验证安装与第一个程序

安装完成后,打开终端(Windows使用CMD或PowerShell),输入以下命令验证:

python --version
# 或者
python3 --version

如果显示类似”Python 3.10.6”的版本信息,说明安装成功。

现在让我们编写第一个Python程序。创建一个名为hello.py的文件:

# hello.py
print("Hello, Python World!")
print("欢迎来到Python编程世界")
print("这是我的第一个程序")

在终端中运行:

python hello.py

你应该能看到三行输出。恭喜,你已经成功迈出了编程的第一步!

1.3 开发工具选择

初学者推荐工具:

  • IDLE:Python自带的简单IDE,适合完全新手
  • VS Code:轻量级但功能强大,安装Python插件后非常好用
  • PyCharm Community:专业级IDE,社区版免费,功能丰富

VS Code配置Python开发环境:

  1. 下载安装VS Code:https://code.visualstudio.com/
  2. 打开VS Code,点击左侧扩展图标(或Ctrl+Shift+X)
  3. 搜索”Python”,安装Microsoft官方提供的Python扩展
  4. 创建一个新文件,保存为.py后缀,即可开始编写代码

第二阶段:Python基础语法深度解析(第3-6周)

2.1 变量与数据类型

Python是动态类型语言,你不需要显式声明变量类型。变量名可以包含字母、数字和下划线,但不能以数字开头。

# 变量赋值示例
name = "Alice"          # 字符串类型
age = 25                # 整数类型
height = 1.65           # 浮点数类型
is_student = True       # 布尔类型

# 查看变量类型
print(type(name))       # <class 'str'>
print(type(age))        # <class 'int'>
print(type(height))     # <class 'float'>
print(type(is_student)) # <class 'bool'>

# 多个变量同时赋值
x, y, z = 1, 2, 3
print(x, y, z)          # 1 2 3

# 变量命名规范
user_name = "Bob"       # 蛇形命名法(推荐)
userName = "Bob"        # 驼峰命名法
_USER_NAME = "Bob"      # 常量(约定俗成)

2.2 字符串操作详解

字符串是Python中最常用的数据类型之一,掌握字符串操作至关重要。

# 字符串创建
single_quote = 'Hello'
double_quote = "World"
triple_quote = """这是
多行
字符串"""

# 字符串拼接
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name  # 使用+号
print(full_name)  # John Doe

# 字符串格式化(三种方式)
age = 25
# 方式1:使用%操作符(旧式)
message1 = "My name is %s and I am %d years old" % (first_name, age)
print(message1)

# 方式2:使用format()方法(推荐)
message2 = "My name is {} and I am {} years old".format(first_name, age)
print(message2)

# 方式3:使用f-string(Python 3.6+,最推荐)
message3 = f"My name is {first_name} and I am {age} years old"
print(message3)

# 常用字符串方法
text = "  Hello Python  "
print(text.strip())        # "Hello Python"(去除空格)
print(text.upper())        # "  HELLO PYTHON  "
print(text.lower())        # "  hello python  "
print(text.split())        # ['', 'Hello', 'Python', ''](按空格分割)
print(text.find("Python")) # 8(查找位置)
print(text.replace("Hello", "Hi"))  # "  Hi Python  "

# 字符串切片(重要!)
s = "Python"
print(s[0])      # P(第一个字符)
print(s[-1])     # n(最后一个字符)
print(s[1:4])    # yth(索引1到3,不包括4)
print(s[:3])     # Pyt(从开始到索引2)
print(s[3:])     # hon(从索引3到结束)
print(s[::2])    # Pto(步长为2)
print(s[::-1])   # nohtyP(反转字符串)

2.3 列表与元组

列表(list)是Python中最灵活的数据结构,可变;元组(tuple)不可变,性能稍好。

# 列表创建与基本操作
fruits = ["apple", "banana", "orange"]
print(fruits)  # ['apple', 'banana', ' 'orange']

# 访问元素
print(fruits[0])   # apple
print(fruits[-1])  # orange(最后一个元素)

# 修改元素
fruits[1] = "grape"
print(fruits)  # ['apple', 'grape', 'orange']

# 列表方法
fruits.append("mango")      # 添加元素
print(fruits)  # ['apple', 'grape', 'orange', 'mango']

fruits.insert(1, "kiwi")    # 在指定位置插入
print(fruits)  # ['apple', 'kiwi', 'grape', 'orange', 'mango']

fruits.remove("grape")      # 删除指定元素
print(fruits)  # ['apple', 'kiwi', 'orange', 'mango']

popped = fruits.pop()       # 删除并返回最后一个元素
print(popped)   # mango
print(fruits)   # ['apple', 'kiwi', 'orange']

# 列表切片(类似字符串)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:6])    # [2, 3, 4, 5]
print(numbers[:3])     # [0, 1, 2]
print(numbers[::2])    # [0, 2, 4, 6, 8]

# 列表推导式(Pythonic写法)
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 元组(不可变列表)
point = (3, 4)
print(point[0])  # 3
# point[0] = 5   # 这会报错!元组不可修改

# 元组解包
x, y = point
print(f"x={x}, y={y}")  # x=3, y=4

# 元组应用场景:函数返回多个值
def get_user_info():
    return "Alice", 25, "alice@example.com"

name, age, email = get_user_info()
print(f"Name: {name}, Age: {age}, Email: {email}")

2.4 字典与集合

字典(dict)是键值对结构,集合(set)是无序不重复元素集。

# 字典创建
person = {
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
}
print(person)  # {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

# 访问字典元素
print(person["name"])  # Alice
print(person.get("age"))  # 25
print(person.get("phone", "N/A"))  # N/A(键不存在时返回默认值)

# 添加/修改元素
person["phone"] = "123-456-7890"  # 添加
person["age"] = 26                 # 修改
print(person)

# 字典方法
keys = person.keys()      # 所有键
values = person.values()  # 所有值
items = person.items()    # 所有键值对

for key, value in items:
    print(f"{key}: {value}")

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 集合(自动去重)
colors = {"red", "blue", "green", "red"}
print(colors)  # {'red', 'blue', 'green'}

# 集合运算
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a | set_b)  # {1, 2, 3, 4, 5} 并集
print(set_a & set_b)  # {3} 交集
print(set_a - set_b)  # {1, 2} 差集
print(set_a ^ set_b)  # {1, 2, 4, 5} 对称差集

# 集合推导式
unique_squares = {x**2 for x in [-2, -1, 0, 1, 2]}
print(unique_squares)  # {0, 1, 4}

2.5 条件语句与循环

# if-elif-else语句
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"分数: {score}, 等级: {grade}")

# 嵌套条件
is_logged_in = True
is_admin = False

if is_logged_in:
    if is_admin:
        print("欢迎管理员!")
    else:
        print("欢迎用户!")
else:
    print("请先登录")

# for循环
# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}")

# 遍历字典
person = {"name": "Alice", "age": 25, "city": "Beijing"}
for key, value in person.items():
    print(f"{key}: {value}")

# range函数
for i in range(5):  # 0到4
    print(i)

for i in range(2, 10, 2):  # 2到8,步长2
    print(i)  # 2, 4, 6, 8

# while循环
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# 循环控制:break和continue
# break示例:找到第一个偶数
numbers = [1, 3, 5, 8, 11, 13]
for num in numbers:
    if num % 2 == 0:
        print(f"找到第一个偶数: {num}")
        break

# continue示例:跳过偶数
for num in range(10):
    if num % 2 == 0:
        continue
    print(num)  # 只打印奇数:1, 3, 5, 7, 9

# 列表推导式中的条件
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

2.6 函数定义与调用

# 基本函数定义
def greet(name):
    """这是一个问候函数"""
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

# 默认参数
def create_person(name, age=18, city="Unknown"):
    return {"name": name, "age": age, "city": city}

person1 = create_person("Bob")
print(person1)  # {'name': 'Bob', 'age': 18, 'city': 'Unknown'}

person2 = create_person("Charlie", 30, "Shanghai")
print(person2)  # {'name': 'Charlie', 'age': 30, 'city': 'Shanghai'}

# 可变参数(*args, **kwargs)
def sum_numbers(*args):
    """计算任意数量数字的和"""
    return sum(args)

print(sum_numbers(1, 2, 3))      # 6
print(sum_numbers(1, 2, 3, 4, 5))  # 15

def print_info(**kwargs):
    """打印任意关键字参数"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Beijing")
# name: Alice
# age: 25
# city: Beijing

# 匿名函数(lambda)
square = lambda x: x**2
print(square(5))  # 25

# lambda在排序中的应用
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]
students_sorted = sorted(students, key=lambda x: x["score"], reverse=True)
print(students_sorted)
# [{'name': 'Bob', 'score': 92}, {'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 78}]

第三阶段:Python核心概念进阶(第7-10周)

3.1 文件操作与异常处理

# 文件读取
try:
    # 写入文件
    with open("example.txt", "w", encoding="utf-8") as f:
        f.write("第一行\n")
        f.write("第二行\n")
        f.write("第三行\n")
    
    # 读取文件
    with open("example.txt", "r", encoding="utf-8") as f:
        content = f.read()
        print("文件内容:")
        print(content)
    
    # 逐行读取
    with open("example.txt", "r", encoding="utf-8") as f:
        print("\n逐行读取:")
        for line_num, line in enumerate(f, 1):
            print(f"第{line_num}行: {line.strip()}")
    
    # 读取大文件(逐行读取,内存友好)
    with open("example.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()  # 读取所有行到列表
        print(f"\n总行数: {len(lines)}")

except FileNotFoundError:
    print("文件不存在!")
except PermissionError:
    print("没有文件访问权限!")
except Exception as e:
    print(f"发生未知错误: {e}")
finally:
    print("文件操作完成")

# 文件模式说明:
# "r"  - 只读(默认)
# "w"  - 只写(覆盖原内容)
# "a"  - 追加(在末尾添加)
# "r+" - 读写
# "w+" - 读写(覆盖)
# "a+" - 读写(追加)
# "b"  - 二进制模式(如"rb", "wb")

3.2 模块与包

# 导入模块的多种方式
import math
print(math.sqrt(16))  # 4.0

from math import sqrt
print(sqrt(16))  # 4.0

from math import sqrt as square_root
print(square_root(16))  # 4.0

from math import *  # 不推荐,容易命名冲突

# 创建自己的模块
# 假设有一个文件 my_utils.py
# 内容如下:
"""
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

PI = 3.14159
"""

# 在另一个文件中使用
# import my_utils
# print(my_utils.add(5, 3))  # 8
# print(my_utils.PI)  # 3.14159

# 包的结构
"""
mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
    ├── __init__.py
    └── module3.py
"""

# 使用包
# from mypackage.module1 import function1
# from mypackage.subpackage.module3 import function3

3.3 面向对象编程(OOP)

# 类与对象
class Dog:
    # 类属性(所有实例共享)
    species = "Canis familiaris"
    
    # 构造方法
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age
    
    # 实例方法
    def bark(self):
        return f"{self.name} says woof!"
    
    def describe(self):
        return f"{self.name} is {self.age} years old"
    
    # 特殊方法
    def __str__(self):
        return f"Dog({self.name}, {self.age})"
    
    def __repr__(self):
        return f"Dog('{self.name}', {self.age})"

# 创建对象
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

print(dog1.bark())      # Buddy says woof!
print(dog1.describe())  # Buddy is 3 years old
print(dog1)             # Dog(Buddy, 3)
print(dog1.species)     # Canis familiaris

# 继承
class Bulldog(Dog):  # 继承自Dog类
    def __init__(self, name, age, weight):
        super().__init__(name, age)  # 调用父类构造方法
        self.weight = weight
    
    def bark(self):  # 方法重写
        return f"{self.name} says WOOF!"
    
    def describe(self):  # 扩展父类方法
        parent_desc = super().describe()
        return f"{parent_desc}, weight: {self.weight}kg"

bulldog = Bulldog("Rocky", 4, 25)
print(bulldog.bark())      # Rocky says WOOF!
print(bulldog.describe())  # Rocky is 4 years old, weight: 25kg

# 封装:使用私有属性和方法
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 f"存入 {amount}, 余额: {self.__balance}"
        return "存款金额必须大于0"
    
    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return f"取出 {amount}, 余额: {self.__balance}"
        return "取款金额不足或无效"
    
    def get_balance(self):  # 提供只读访问
        return self.__balance
    
    # 使用property装饰器
    @property
    def balance(self):
        return self.__balance

account = BankAccount("Alice", 1000)
print(account.deposit(500))   # 存入 500, 余额: 1500
print(account.withdraw(200))  # 取出 200, 余额: 1300
print(account.balance)        # 1300(使用property)
# print(account.__balance)    # 报错!无法直接访问私有属性

3.4 迭代器与生成器

# 自定义迭代器
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

# 使用迭代器
cd = Countdown(5)
for num in cd:
    print(num)  # 5, 4, 3, 2, 1

# 生成器(更简洁的方式)
def countdown_generator(start):
    for i in range(start, 0, -1):
        yield i

# 使用生成器
for num in countdown_generator(5):
    print(num)  # 5, 4, 3, 2, 1

# 生成器表达式(类似列表推导式,但返回生成器)
# 列表推导式:一次性生成所有元素,占用内存
squares_list = [x**2 for x in range(1000000)]

# 生成器表达式:按需生成,节省内存
squares_gen = (x**2 for x in range(1000000))

# 使用next()逐个获取
print(next(squares_gen))  # 0
print(next(squares_gen))  # 1
print(next(squares_gen))  # 4

第四阶段:Python常用标准库与实战项目(第11-14周)

4.1 datetime库:时间日期处理

from datetime import datetime, date, timedelta

# 获取当前时间
now = datetime.now()
print(f"当前时间: {now}")  # 2024-01-15 14:30:25.123456

# 创建特定时间
specific_date = datetime(2024, 12, 25, 18, 30, 0)
print(f"圣诞节: {specific_date}")

# 格式化时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"格式化: {formatted}")  # 2024-01-15 14:30:25

# 解析字符串为时间
date_str = "2024-01-15 14:30:25"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"解析结果: {parsed}")

# 时间运算
future = now + timedelta(days=7, hours=2)
print(f"7天2小时后: {future}")

past = now - timedelta(weeks=1)
print(f"1周前: {past}")

# 计算时间差
diff = future - now
print(f"时间差: {diff}")  # 7 days, 2:00:00
print(f"总秒数: {diff.total_seconds()}")

# 日期对象
today = date.today()
print(f"今天: {today}")
print(f"年: {today.year}, 月: {today.month}, 日: {today.day}")

4.2 re库:正则表达式

import re

# 基本匹配
text = "我的电话是138-1234-5678,邮箱是user@example.com"
pattern = r"\d{3}-\d{4}-\d{4}"  # 匹配电话号码
match = re.search(pattern, text)
if match:
    print(f"找到电话: {match.group()}")  # 138-1234-5678

# 邮箱匹配
email_pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(email_pattern, text)
print(f"找到邮箱: {emails}")  # ['user@example.com']

# 分组提取
text = "订单号: ORD-2024-001, 金额: 125.50元"
pattern = r"订单号: (ORD-\d{4}-\d{3}), 金额: (\d+\.\d+)元"
match = re.search(pattern, text)
if match:
    order_num = match.group(1)
    amount = match.group(2)
    print(f"订单: {order_num}, 金额: {amount}")

# 替换
text = "今天是2024-01-15,明天是2024-01-16"
new_text = re.sub(r"\d{4}-\d{2}-\d{2}", "日期", text)
print(f"替换后: {今天是日期,明天是日期}")

# 分割
text = "apple,banana;orange|grape"
result = re.split(r"[,;|]", text)
print(f"分割结果: {result}")  # ['apple', 'banana', 'orange', 'grape']

# 编译正则表达式(提高重复使用性能)
phone_pattern = re.compile(r"\d{3}-\d{4}-\d{4}")
text1 = "电话1: 138-1234-5678"
text2 = "电话2: 139-8765-4321"
print(phone_pattern.search(text1).group())  # 138-1234-5678
print(phone_pattern.search(text2).group())  # 139-8765-4321

4.3 os与sys库:系统操作

import os
import sys

# 文件路径操作
current_dir = os.getcwd()
print(f"当前目录: {current_dir}")

# 路径拼接(自动处理不同操作系统的路径分隔符)
config_path = os.path.join(current_dir, "config", "settings.ini")
print(f"配置文件路径: {config_path}")

# 检查路径是否存在
if os.path.exists(config_path):
    print("路径存在")
else:
    print("路径不存在")

# 创建目录
new_dir = os.path.join(current_dir, "temp")
if not os.path.exists(new_dir):
    os.makedirs(new_dir)  # 递归创建多层目录
    print(f"创建目录: {new_dir}")

# 列出目录内容
files = os.listdir(current_dir)
print(f"当前目录文件: {files}")

# 遍历目录(递归)
for root, dirs, files in os.walk(current_dir):
    print(f"目录: {root}")
    print(f"子目录: {dirs}")
    print(f"文件: {files}")
    break  # 只显示第一层

# 文件信息
file_path = __file__  # 当前脚本路径
print(f"文件大小: {os.path.getsize(file_path)} 字节")
print(f"修改时间: {os.path.getmtime(file_path)}")

# sys模块
print(f"Python版本: {sys.version}")
print(f"脚本名称: {sys.argv[0]}")
print(f"命令行参数: {sys.argv}")

# 退出程序
# sys.exit(0)  # 正常退出
# sys.exit(1)  # 错误退出

4.4 实战项目1:文件整理器

import os
import shutil
from datetime import datetime

def organize_files(directory, extensions_map):
    """
    文件整理器:根据文件扩展名自动分类到不同文件夹
    
    Args:
        directory: 要整理的目录路径
        extensions_map: 扩展名到文件夹的映射字典
            例如: {'.jpg': 'Images', '.pdf': 'Documents'}
    """
    if not os.path.exists(directory):
        print(f"目录不存在: {directory}")
        return
    
    # 创建目标文件夹
    for folder in extensions_map.values():
        folder_path = os.path.join(directory, folder)
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
            print(f"创建文件夹: {folder}")
    
    # 统计信息
    moved_count = 0
    skipped_count = 0
    
    # 遍历目录
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        
        # 跳过目录和已存在的目标文件夹
        if os.path.isdir(file_path) or filename in extensions_map.values():
            skipped_count += 1
            continue
        
        # 获取文件扩展名(转换为小写)
        _, ext = os.path.splitext(filename)
        ext = ext.lower()
        
        # 根据扩展名移动文件
        if ext in extensions_map:
            target_folder = extensions_map[ext]
            target_path = os.path.join(directory, target_folder, filename)
            
            try:
                shutil.move(file_path, target_path)
                print(f"移动: {filename} -> {target_folder}")
                moved_count += 1
            except Exception as e:
                print(f"移动失败 {filename}: {e}")
                skipped_count += 1
        else:
            skipped_count += 1
    
    print(f"\n整理完成!")
    print(f"移动文件: {moved_count} 个")
    print(f"跳过文件: {skipped_count} 个")

# 使用示例
if __name__ == "__main__":
    # 定义文件类型映射
    file_types = {
        # 图片
        '.jpg': 'Images', '.jpeg': 'Images', '.png': 'Images', '.gif': 'Images',
        # 文档
        '.pdf': 'Documents', '.doc': 'Documents', '.docx': 'Documents', '.txt': 'Documents',
        # 音频
        '.mp3': 'Music', '.wav': 'Music', '.flac': 'Music',
        # 视频
        '.mp4': 'Videos', '.avi': 'Videos', '.mkv': 'Videos',
        # 压缩包
        '.zip': 'Archives', '.rar': 'Archives', '.7z': 'Archives',
        # 代码
        '.py': 'Code', '.js': 'Code', '.html': 'Code', '.css': 'Code',
    }
    
    # 要整理的目录(修改为你的目录)
    target_directory = "./downloads"  # 当前目录下的downloads文件夹
    
    # 执行整理
    organize_files(target_directory, file_types)

4.5 实战项目2:简易通讯录管理系统

import json
import os

class ContactManager:
    """通讯录管理系统"""
    
    def __init__(self, storage_file="contacts.json"):
        self.storage_file = storage_file
        self.contacts = []
        self.load_contacts()
    
    def load_contacts(self):
        """从文件加载联系人"""
        if os.path.exists(self.storage_file):
            try:
                with open(self.storage_file, "r", encoding="utf-8") as f:
                    self.contacts = json.load(f)
                print(f"已加载 {len(self.contacts)} 个联系人")
            except Exception as e:
                print(f"加载失败: {e}")
                self.contacts = []
        else:
            self.contacts = []
    
    def save_contacts(self):
        """保存联系人到文件"""
        try:
            with open(self.storage_file, "w", encoding="utf-8") as f:
                json.dump(self.contacts, f, ensure_ascii=False, indent=2)
            print("保存成功!")
        except Exception as e:
            print(f"保存失败: {e}")
    
    def add_contact(self):
        """添加联系人"""
        print("\n=== 添加联系人 ===")
        name = input("姓名: ").strip()
        if not name:
            print("姓名不能为空!")
            return
        
        phone = input("电话: ").strip()
        email = input("邮箱: ").strip()
        
        contact = {
            "id": len(self.contacts) + 1,
            "name": name,
            "phone": phone,
            "email": email
        }
        
        self.contacts.append(contact)
        print(f"✓ 成功添加联系人: {name}")
    
    def search_contact(self):
        """搜索联系人"""
        print("\n=== 搜索联系人 ===")
        keyword = input("输入姓名或电话关键词: ").strip().lower()
        
        results = [
            c for c in self.contacts
            if keyword in c["name"].lower() or keyword in c["phone"]
        ]
        
        if not results:
            print("未找到匹配的联系人")
            return
        
        print(f"\n找到 {len(results)} 个联系人:")
        self._display_contacts(results)
    
    def display_all_contacts(self):
        """显示所有联系人"""
        print("\n=== 所有联系人 ===")
        if not self.contacts:
            print("通讯录为空")
            return
        
        self._display_contacts(self.contacts)
    
    def _display_contacts(self, contacts):
        """辅助方法:格式化显示联系人"""
        for contact in contacts:
            print(f"ID: {contact['id']}")
            print(f"姓名: {contact['name']}")
            print(f"电话: {contact['phone']}")
            print(f"邮箱: {contact['email']}")
            print("-" * 30)
    
    def delete_contact(self):
        """删除联系人"""
        print("\n=== 删除联系人 ===")
        self.display_all_contacts()
        
        try:
            contact_id = int(input("输入要删除的联系人ID: "))
            for i, contact in enumerate(self.contacts):
                if contact["id"] == contact_id:
                    confirm = input(f"确认删除 {contact['name']}? (y/n): ")
                    if confirm.lower() == 'y':
                        del self.contacts[i]
                        print("✓ 删除成功")
                    else:
                        print("已取消删除")
                    return
            print("未找到该ID的联系人")
        except ValueError:
            print("请输入有效的数字ID")
    
    def edit_contact(self):
        """编辑联系人"""
        print("\n=== 编辑联系人 ===")
        self.display_all_contacts()
        
        try:
            contact_id = int(input("输入要编辑的联系人ID: "))
            for contact in self.contacts:
                if contact["id"] == contact_id:
                    print(f"\n当前信息: {contact}")
                    name = input(f"姓名 [{contact['name']}]: ").strip()
                    phone = input(f"电话 [{contact['phone']}]: ").strip()
                    email = input(f"邮箱 [{contact['email']}]: ").strip()
                    
                    if name: contact["name"] = name
                    if phone: contact["phone"] = phone
                    if email: contact["email"] = email
                    
                    print("✓ 更新成功")
                    return
            print("未找到该ID的联系人")
        except ValueError:
            print("请输入有效的数字ID")
    
    def run(self):
        """主循环"""
        while True:
            print("\n" + "="*40)
            print("通讯录管理系统")
            print("="*40)
            print("1. 添加联系人")
            print("2. 搜索联系人")
            print("3. 显示所有联系人")
            print("4. 删除联系人")
            print("5. 编辑联系人")
            print("6. 保存并退出")
            print("="*40)
            
            choice = input("请选择操作 (1-6): ").strip()
            
            if choice == "1":
                self.add_contact()
            elif choice == "2":
                self.search_contact()
            elif choice == "3":
                self.display_all_contacts()
            elif choice == "4":
                self.delete_contact()
            elif choice == "5":
                self.edit_contact()
            elif choice == "6":
                self.save_contacts()
                print("再见!")
                break
            else:
                print("无效选择,请重新输入")

# 使用示例
if __name__ == "__main__":
    manager = ContactManager()
    manager.run()

第五阶段:Python高级主题与性能优化(第15-18周)

5.1 装饰器(Decorators)

import time
import functools

# 基础装饰器:计时器
def timer(func):
    @functools.wraps(func)  # 保留原函数的元信息
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
        return result
    return wrapper

@timer
def slow_function():
    """模拟耗时操作"""
    time.sleep(1)
    return "完成"

# 带参数的装饰器
def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def greet(name):
    print(f"Hello, {name}!")

# 类装饰器
class Memoize:
    def __init__(self, func):
        self.func = func
        self.cache = {}
    
    def __call__(self, *args):
        if args in self.cache:
            return self.cache[args]
        result = self.func(*args)
        self.cache[args] = result
        return result

@Memoize
def fibonacci(n):
    """计算斐波那契数列(递归)"""
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 使用示例
if __name__ == "__main__":
    # 测试计时器
    print(slow_function())
    
    # 测试重复装饰器
    greet("Alice")
    
    # 测试缓存装饰器
    print(f"Fibonacci(30) = {fibonacci(30)}")

5.2 上下文管理器(Context Managers)

from contextlib import contextmanager
import time

# 使用类实现上下文管理器
class Timer:
    def __init__(self, name="Timer"):
        self.name = name
    
    def __enter__(self):
        self.start = time.time()
        print(f"{self.name} 开始计时")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print(f"{self.name} 结束,耗时: {self.end - self.start:.4f}秒")
        # 如果返回True,会抑制异常
        return False

# 使用示例
with Timer("数据处理"):
    time.sleep(1)
    print("处理中...")

# 使用contextmanager装饰器
@contextmanager
def temporary_file(content):
    """创建临时文件并自动删除"""
    import tempfile
    import os
    
    # 创建临时文件
    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as f:
            f.write(content)
        yield path  # 返回路径给with块使用
    finally:
        # 清理临时文件
        if os.path.exists(path):
            os.remove(path)
            print(f"已删除临时文件: {path}")

# 使用示例
with temporary_file("临时数据") as temp_path:
    print(f"临时文件路径: {temp_path}")
    with open(temp_path, 'r') as f:
        print(f"内容: {f.read()}")

5.3 多线程与多进程

import threading
import multiprocessing
import time
import requests
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# 多线程示例:并发下载
def download_url(url):
    """模拟下载任务"""
    try:
        response = requests.get(url, timeout=5)
        return f"{url}: {len(response.content)} 字节"
    except Exception as e:
        return f"{url}: 失败 - {e}"

def multi_thread_download():
    """使用线程池并发下载"""
    urls = [
        "https://httpbin.org/delay/1",
        "https://httpbin.org/delay/1",
        "https://httpbin.org/delay/1",
    ]
    
    start = time.time()
    with ThreadPoolExecutor(max_workers=3) as executor:
        results = list(executor.map(download_url, urls))
    
    print(f"多线程耗时: {time.time() - start:.2f}秒")
    for result in results:
        print(result)

# 多进程示例:CPU密集型任务
def heavy_calculation(n):
    """CPU密集型计算"""
    return sum(i * i for i in range(n))

def multi_process_calc():
    """使用进程池处理CPU密集型任务"""
    numbers = [10_000_000, 10_000_000, 10_000_000]
    
    start = time.time()
    with ProcessPoolExecutor(max_workers=3) as executor:
        results = list(executor.map(heavy_calculation, numbers))
    
    print(f"多进程耗时: {time.time() - start:.2f}秒")
    print(f"结果: {results}")

# 线程锁示例:避免竞态条件
class Counter:
    def __init__(self):
        self.value = 0
        self.lock = threading.Lock()
    
    def increment(self):
        with self.lock:
            self.value += 1

def safe_increment(counter, times):
    for _ in range(times):
        counter.increment()

# 使用示例
if __name__ == "__main__":
    # 注意:多进程代码需要在if __name__ == "__main__"中运行
    
    print("=== 多线程下载测试 ===")
    multi_thread_download()
    
    print("\n=== 多进程计算测试 ===")
    multi_process_calc()
    
    print("\n=== 线程安全计数器 ===")
    counter = Counter()
    threads = []
    for _ in range(10):
        t = threading.Thread(target=safe_increment, args=(counter, 1000))
        threads.append(t)
        t.start()
    
    for t in threads:
        t.join()
    
    print(f"最终计数: {counter.value}")  # 应该是10000

5.4 性能优化技巧

# 1. 使用列表推导式替代循环
import time

def test_performance():
    # 慢方法:普通循环
    start = time.time()
    result1 = []
    for i in range(100000):
        if i % 2 == 0:
            result1.append(i * 2)
    time1 = time.time() - start
    
    # 快方法:列表推导式
    start = time.time()
    result2 = [i * 2 for i in range(100000) if i % 2 == 0]
    time2 = time.time() - start
    
    print(f"普通循环: {time1:.4f}秒")
    print(f"列表推导式: {time2:.4f}秒")
    print(f"性能提升: {time1/time2:.2f}倍")

# 2. 使用生成器处理大数据
def process_large_file(filename):
    """逐行处理大文件,内存友好"""
    with open(filename, 'r') as f:
        for line in f:
            # 处理每一行
            yield line.strip()

# 3. 使用join拼接字符串
def string_concat():
    # 慢:使用+拼接
    start = time.time()
    result = ""
    for i in range(10000):
        result += str(i)
    time1 = time.time() - start
    
    # 快:使用join
    start = time.time()
    result = "".join(str(i) for i in range(10000))
    time2 = time.time() - start
    
    print(f"使用+拼接: {time1:.4f}秒")
    print(f"使用join: {time2:.4f}秒")

# 4. 使用内置函数
def builtin_vs_custom():
    # 内置sum比手动循环快
    numbers = list(range(1000000))
    
    start = time.time()
    total1 = sum(numbers)
    time1 = time.time() - start
    
    start = time.time()
    total2 = 0
    for n in numbers:
        total2 += n
    time2 = time.time() - start
    
    print(f"内置sum: {time1:.4f}秒")
    print(f"手动循环: {time2:.4f}秒")

# 5. 使用lru_cache缓存
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci_cached(n):
    """带缓存的斐波那契"""
    if n < 2:
        return n
    return fibonacci_cached(n-1) + fibonacci_cached(n-2)

# 性能测试
if __name__ == "__main__":
    print("=== 性能测试 ===")
    test_performance()
    print("\n=== 字符串拼接测试 ===")
    string_concat()
    print("\n=== 内置函数测试 ===")
    builtin_vs_custom()
    
    # 缓存性能对比
    import sys
    sys.setrecursionlimit(2000)  # 提高递归限制
    
    start = time.time()
    result1 = fibonacci_cached(300)
    time1 = time.time() - start
    
    start = time.time()
    result2 = fibonacci_cached(300)  # 第二次调用,直接从缓存读取
    time2 = time.time() - start
    
    print(f"\n首次计算斐波那契(300): {time1:.4f}秒")
    print(f"缓存后计算: {time2:.4f}秒")
    print(f"性能提升: {time1/time2:.0f}倍")

第六阶段:常见难题与解决方案(持续更新)

6.1 编码问题

问题: UnicodeDecodeError: ‘utf-8’ codec can’t decode byte…

解决方案:

# 1. 指定正确编码读取
try:
    with open("file.txt", "r", encoding="utf-8") as f:
        content = f.read()
except UnicodeDecodeError:
    # 尝试其他编码
    with open("file.txt", "r", encoding="gbk") as f:
        content = f.read()

# 2. 自动检测编码(需要chardet库)
# pip install chardet
import chardet

def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        raw_data = f.read(10000)  # 读取前10KB检测
        result = chardet.detect(raw_data)
        return result['encoding']

# 3. 宽容模式读取
with open("file.txt", "r", encoding="utf-8", errors="ignore") as f:
    content = f.read()  # 忽略错误字符

# 4. 写入时确保编码
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("中文内容")

6.2 内存溢出问题

问题: 处理大文件时内存不足

解决方案:

# 1. 逐行读取大文件
def process_large_file_line_by_line(filename):
    """逐行处理,内存占用恒定"""
    with open(filename, 'r', encoding='utf-8') as f:
        for line in f:
            # 处理每一行
            process_line(line)

# 2. 使用生成器
def read_large_file(filename):
    """生成器逐行读取"""
    with open(filename, 'r', encoding='utf-8') as f:
        for line in f:
            yield line.strip()

# 3. 分块读取
def read_in_chunks(filename, chunk_size=8192):
    """分块读取大文件"""
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            yield chunk

# 4. 使用pandas处理大数据(分块读取CSV)
import pandas as pd

def process_large_csv(filename):
    """分块读取CSV"""
    chunk_iter = pd.read_csv(filename, chunksize=10000)
    for chunk in chunk_iter:
        # 处理每个chunk
        process_chunk(chunk)

# 5. 及时释放对象
def memory_efficient_processing():
    """及时释放不再需要的对象"""
    large_list = list(range(10000000))
    # 处理数据...
    result = sum(large_list)
    # 及时删除大对象
    del large_list
    return result

6.3 递归深度限制

问题: RecursionError: maximum recursion depth exceeded

解决方案:

import sys
from functools import lru_cache

# 1. 增加递归限制(谨慎使用)
sys.setrecursionlimit(10000)  # 默认是1000

# 2. 使用迭代替代递归
def factorial_recursive(n):
    """递归版本(可能栈溢出)"""
    if n <= 1:
        return 1
    return n * factorial_recursive(n-1)

def factorial_iterative(n):
    """迭代版本(安全)"""
    result = 1
    for i in range(2, n+1):
        result *= i
    return result

# 3. 使用尾递归优化(Python不支持,但可以手动优化)
def factorial_tail_recursive(n, accumulator=1):
    """手动尾递归优化"""
    if n <= 1:
        return accumulator
    return factorial_tail_recursive(n-1, accumulator * n)

# 4. 使用lru_cache减少递归调用
@lru_cache(maxsize=None)
def fibonacci_optimized(n):
    """带缓存的斐波那契"""
    if n < 2:
        return n
    return fibonacci_optimized(n-1) + fibonacci_optimized(n-2)

# 5. 使用栈模拟递归
def fibonacci_stack(n):
    """用栈模拟递归,避免栈溢出"""
    if n < 2:
        return n
    
    stack = [(n, None)]
    results = {}
    
    while stack:
        current, _ = stack[-1]
        
        if current < 2:
            results[current] = current
            stack.pop()
            continue
        
        # 检查子问题是否已解决
        if current - 1 in results and current - 2 in results:
            results[current] = results[current - 1] + results[current - 2]
            stack.pop()
        else:
            # 添加子问题
            if current - 1 not in results:
                stack.append((current - 1, None))
            if current - 2 not in results:
                stack.append((current - 2, None))
    
    return results[n]

6.4 并发与竞态条件

问题: 多线程/多进程中的数据竞争

解决方案:

import threading
import multiprocessing
from queue import Queue
import time

# 1. 使用线程锁(Lock)
class SafeCounter:
    def __init__(self):
        self.value = 0
        self.lock = threading.Lock()
    
    def increment(self):
        with self.lock:
            self.value += 1

# 2. 使用RLock(可重入锁)
class ReentrantCounter:
    def __init__(self):
        self.value = 0
        self.rlock = threading.RLock()
    
    def increment(self):
        with self.rlock:
            self.value += 1
    
    def increment_twice(self):
        with self.rlock:
            self.increment()  # 可以在持有锁时再次获取
            self.increment()

# 3. 使用线程安全队列
def producer(queue, items):
    """生产者"""
    for item in items:
        time.sleep(0.1)
        queue.put(item)
        print(f"生产: {item}")

def consumer(queue):
    """消费者"""
    while True:
        item = queue.get()
        if item is None:  # 结束信号
            break
        print(f"消费: {item}")
        queue.task_done()

def thread_safe_queue_example():
    """使用队列实现线程间安全通信"""
    q = Queue()
    
    # 启动生产者线程
    producer_thread = threading.Thread(target=producer, args=(q, [1, 2, 3, 4, 5]))
    producer_thread.start()
    
    # 启动消费者线程
    consumer_thread = threading.Thread(target=consumer, args=(q,))
    consumer_thread.start()
    
    # 等待生产者完成
    producer_thread.join()
    
    # 发送结束信号
    q.put(None)
    
    # 等待消费者完成
    consumer_thread.join()

# 4. 使用进程间通信(multiprocessing.Queue)
def process_worker(queue, data):
    """进程工作函数"""
    result = sum(data)
    queue.put(result)

def multiprocessing_example():
    """多进程安全通信"""
    q = multiprocessing.Queue()
    processes = []
    
    # 创建多个进程
    for i in range(3):
        data = list(range(i*1000, (i+1)*1000))
        p = multiprocessing.Process(target=process_worker, args=(q, data))
        processes.append(p)
        p.start()
    
    # 等待所有进程完成
    for p in processes:
        p.join()
    
    # 收集结果
    results = []
    while not q.empty():
        results.append(q.get())
    
    print(f"多进程结果: {results}")

# 5. 使用原子操作(对于简单操作)
from threading import Lock

class AtomicCounter:
    """使用Lock实现原子操作"""
    def __init__(self):
        self._value = 0
        self._lock = Lock()
    
    @property
    def value(self):
        with self._lock:
            return self._value
    
    def increment(self, amount=1):
        with self._lock:
            self._value += amount
            return self._value

# 使用示例
if __name__ == "__main__":
    print("=== 线程安全计数器 ===")
    counter = SafeCounter()
    threads = []
    for _ in range(100):
        t = threading.Thread(target=counter.increment)
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
    print(f"安全计数: {counter.value}")  # 100
    
    print("\n=== 线程安全队列 ===")
    thread_safe_queue_example()
    
    print("\n=== 多进程示例 ===")
    multiprocessing_example()

6.5 包管理与依赖冲突

问题: 不同项目需要不同版本的包

解决方案:

# 1. 使用虚拟环境(强烈推荐)
# 创建虚拟环境
python -m venv myproject_env

# 激活虚拟环境
# Windows:
myproject_env\Scripts\activate
# macOS/Linux:
source myproject_env/bin/activate

# 在虚拟环境中安装包
pip install requests==2.28.1
pip install pandas==1.5.0

# 查看已安装包
pip list

# 导出依赖
pip freeze > requirements.txt

# 从requirements.txt安装
pip install -r requirements.txt

# 2. 使用pipenv(更高级的依赖管理)
# 安装pipenv
pip install pipenv

# 创建新环境
pipenv install requests==2.28.1

# 激活环境
pipenv shell

# 3. 使用conda(适合数据科学)
# 创建环境
conda create -n myenv python=3.9

# 激活环境
conda activate myenv

# 安装包
conda install pandas numpy

# 4. 解决依赖冲突
# 使用pip check检查冲突
pip check

# 使用pipdeptree查看依赖树
pip install pipdeptree
pipdeptree

# 5. 使用Docker隔离环境
# Dockerfile示例
"""
FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

CMD ["python", "main.py"]
"""

第七阶段:学习资源与进阶路径

7.1 推荐学习资源

在线教程:

练习平台:

  • LeetCode:算法与数据结构练习
  • HackerRank:Python专项练习
  • Codewars:趣味编程挑战
  • Exercism:导师指导的练习

视频课程:

  • Coursera:Python for Everybody(密歇根大学)
  • Udemy:Complete Python Bootcamp
  • B站:搜索”Python入门”有大量优质免费视频

7.2 项目驱动学习路径

第1个月:基础语法

  • 项目:计算器、猜数字游戏、文本处理工具

第2个月:数据结构

  • 项目:通讯录、待办事项管理器、简单爬虫

第3个月:文件与网络

  • 项目:文件整理器、天气查询工具、简易博客系统

第4个月:数据库与Web

  • 项目:Flask/Django博客、用户管理系统

第5个月:数据分析

  • 项目:股票数据分析、销售数据可视化

第6个月:机器学习入门

  • 项目:手写数字识别、电影推荐系统

7.3 常见错误与调试技巧

# 1. 使用print调试(简单但有效)
def debug_print():
    x = 10
    y = 0
    print(f"调试: x={x}, y={y}")  # 检查变量值
    try:
        result = x / y
    except ZeroDivisionError as e:
        print(f"错误: {e}")  # 打印错误信息
        import traceback
        traceback.print_exc()  # 打印完整堆栈

# 2. 使用logging模块(专业调试)
import logging

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('debug.log'),
        logging.StreamHandler()
    ]
)

def debug_logging():
    logging.debug("这是调试信息")
    logging.info("这是普通信息")
    logging.warning("这是警告信息")
    logging.error("这是错误信息")

# 3. 使用pdb调试器
def debug_pdb():
    import pdb
    x = 10
    y = 0
    pdb.set_trace()  # 程序会在这里暂停,进入交互式调试
    result = x / y
    return result

# 4. 使用断言
def debug_assert():
    def divide(a, b):
        assert b != 0, "除数不能为0"
        return a / b
    
    try:
        divide(10, 0)
    except AssertionError as e:
        print(f"断言错误: {e}")

# 5. 使用IDE调试器(VS Code/PyCharm)
# 在VS Code中:
# 1. 在代码行号左侧点击设置断点(红点)
# 2. 按F5启动调试
# 3. 可以查看变量、单步执行、调用栈

# 6. 常见错误类型与处理
def common_errors():
    # 1. NameError:变量未定义
    try:
        print(undefined_var)
    except NameError as e:
        print(f"变量未定义: {e}")
    
    # 2. TypeError:类型错误
    try:
        result = "hello" + 123
    except TypeError as e:
        print(f"类型错误: {e}")
    
    # 3. IndexError:索引越界
    try:
        arr = [1, 2, 3]
        print(arr[5])
    except IndexError as e:
        print(f"索引越界: {e}")
    
    # 4. KeyError:字典键不存在
    try:
        d = {"a": 1}
        print(d["b"])
    except KeyError as e:
        print(f"键不存在: {e}")
    
    # 5. AttributeError:属性不存在
    try:
        "hello".nonexistent_method()
    except AttributeError as e:
        print(f"属性不存在: {e}")
    
    # 6. ImportError:导入失败
    try:
        import nonexistent_module
    except ImportError as e:
        print(f"导入失败: {e}")
    
    # 7. FileNotFoundError:文件不存在
    try:
        with open("nonexistent.txt", "r") as f:
            f.read()
    except FileNotFoundError as e:
        print(f"文件不存在: {e}")

# 7. 使用try-except-else-finally
def comprehensive_error_handling():
    try:
        f = open("data.txt", "r")
        data = f.read()
    except FileNotFoundError:
        print("文件不存在,创建新文件")
        f = open("data.txt", "w")
        f.write("默认数据")
    else:
        print("文件读取成功")
    finally:
        if 'f' in locals():
            f.close()
        print("清理完成")

7.4 代码规范与最佳实践

# 1. PEP 8代码风格
# 命名规范
variable_name = "snake_case"  # 变量和函数
ClassName = "CamelCase"      # 类
CONSTANT_NAME = "UPPER_CASE"  # 常量
_private = "私有成员"          # 约定私有

# 缩进:4个空格(不要用Tab)
def correct_indentation():
    if True:
        print("正确缩进")  # 4个空格
        # print("错误缩进")  # 不要用Tab

# 行长度:不超过79字符(最多99字符)
# 使用括号自动换行
long_string = (
    "这是一个很长的字符串,"
    "它被自动换行了"
)

# 空格使用
# 好
result = (a + b) * (c - d)
# 不好
result = (a+b)*(c-d)

# 2. 文档字符串(Docstrings)
def calculate_area(radius):
    """
    计算圆的面积
    
    Args:
        radius (float): 圆的半径
        
    Returns:
        float: 圆的面积
        
    Raises:
        ValueError: 当半径为负数时
        
    Example:
        >>> calculate_area(5)
        78.53981633974483
    """
    if radius < 0:
        raise ValueError("半径不能为负数")
    import math
    return math.pi * radius ** 2

# 3. 类型提示(Python 3.5+)
from typing import List, Dict, Optional, Union

def greet(name: str, age: int = 18) -> str:
    """带类型提示的函数"""
    return f"Hello {name}, age {age}"

def process_data(
    data: List[Dict[str, Union[int, str]]],
    filter_key: Optional[str] = None
) -> List[Dict[str, Union[int, str]]]:
    """处理复杂数据结构"""
    if filter_key:
        return [item for item in data if filter_key in item]
    return data

# 4. 使用__name__ == "__main__"
def main():
    """主函数"""
    print("程序开始执行")
    # 你的代码

if __name__ == "__main__":
    main()  # 只有直接运行脚本时才执行

# 5. 避免使用全局变量
# 不好
global_var = 0

def increment_global():
    global global_var
    global_var += 1

# 好
class Counter:
    def __init__(self):
        self.value = 0
    
    def increment(self):
        self.value += 1

# 6. 使用enumerate而不是range(len())
# 不好
items = ["a", "b", "c"]
for i in range(len(items)):
    print(f"{i}: {items[i]}")

# 好
for i, item in enumerate(items):
    print(f"{i}: {item}")

# 7. 使用with语句管理资源
# 不好
f = open("file.txt", "r")
content = f.read()
f.close()  # 可能忘记关闭

# 好
with open("file.txt", "r") as f:
    content = f.read()  # 自动关闭

# 8. 使用列表推导式、生成器表达式
# 不好
squares = []
for i in range(10):
    squares.append(i**2)

# 好
squares = [i**2 for i in range(10)]

# 9. 使用字典.get()避免KeyError
# 不好
value = my_dict["key"]  # 可能报错

# 好
value = my_dict.get("key", default_value)

# 10. 使用f-string格式化(Python 3.6+)
name = "Alice"
age = 25
# 不好
message = "Name: %s, Age: %d" % (name, age)
# 较好
message = "Name: {}, Age: {}".format(name, age)
# 最好
message = f"Name: {name}, Age: {age}"

结语:持续学习与社区参与

学习Python是一个持续的过程。掌握基础后,建议你:

  1. 阅读优秀代码:在GitHub上阅读热门Python项目的源码
  2. 参与开源项目:从修复小bug或添加文档开始
  3. 写技术博客:记录你的学习过程和项目经验
  4. 参加编程竞赛:如Codeforces、AtCoder等
  5. 关注Python社区:Reddit的r/Python、Python官方邮件列表

记住,编程不是死记硬背,而是解决问题的工具。多写代码,多思考,多总结,你一定能成为Python高手!

最后的建议:

  • 每天至少写1小时代码
  • 遇到问题先自己思考,再搜索解决方案
  • 不要追求完美,先让代码跑起来,再逐步优化
  • 保持好奇心,持续学习新技术

祝你Python学习之旅顺利!🚀