Python 详细教程

目录

  1. Python简介
  2. 安装与环境配置
  3. 基础语法和数据类型
  4. 数据结构
  5. 控制流程
  6. 函数编程
  7. 文件操作
  8. 面向对象编程
  9. 错误和异常处理
  10. 模块和包
  11. 数据科学库
  12. Web开发
  13. 自动化脚本
  14. 最佳实践

1. Python简介

什么是Python?

Python是一种高级、解释型、通用的编程语言,由Guido van Rossum于1991年创建。它以简洁的语法和强大的功能而闻名。

Python的特点

  • 简单易学,语法清晰
  • 跨平台(Windows, macOS, Linux)
  • 丰富的第三方库
  • 面向对象和函数式编程支持
  • 强大的社区支持
  • 广泛应用于Web开发、数据科学、人工智能等领域

Python应用领域

  • Web开发(Django, Flask)
  • 数据科学与机器学习(Pandas, NumPy, Scikit-learn)
  • 自动化脚本
  • 网络爬虫
  • 游戏开发
  • 科学计算

2. 安装与环境配置

安装Python

  1. 访问官网:https://www.python.org/
  2. 下载对应操作系统的安装包
  3. 安装时勾选"Add Python to PATH"

验证安装

1
2
3
4
5
6
# 命令行验证
python --version
python3 --version

# 进入Python交互模式
python

安装开发工具

推荐IDE:

  • PyCharm(专业版)
  • VS Code(免费)
  • Jupyter Notebook(数据科学)

包管理工具pip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 安装包
pip install package_name

# 升级包
pip install --upgrade package_name

# 卸载包
pip uninstall package_name

# 查看已安装包
pip list

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

3. 基础语法和数据类型

第一个Python程序

1
2
# hello.py
print("Hello, World!")

运行程序:

1
python hello.py

变量和赋值

1
2
3
4
5
6
7
8
9
10
11
12
# 变量赋值
name = "Alice"
age = 25
height = 1.65
is_student = True

# 多重赋值
x, y, z = 1, 2, 3
a = b = c = 0

# 交换变量值
x, y = y, x

基本数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 整型
age = 25
print(type(age)) # <class 'int'>

# 浮点型
price = 19.99
print(type(price)) # <class 'float'>

# 字符串
name = "Alice"
message = 'Hello, World!'
print(type(name)) # <class 'str'>

# 布尔型
is_active = True
is_admin = False
print(type(is_active)) # <class 'bool'>

# 空值
result = None
print(type(result)) # <class 'NoneType'>

基本运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 算术运算
a = 10 + 5 # 加法
b = 10 - 5 # 减法
c = 10 * 5 # 乘法
d = 10 / 3 # 除法(浮点数)
e = 10 // 3 # 整除
f = 10 % 3 # 取余
g = 2 ** 3 # 幂运算

# 比较运算
print(10 > 5) # True
print(10 == 5) # False
print(10 != 5) # True
print(10 <= 10) # True

# 逻辑运算
print(True and False) # False
print(True or False) # True
print(not True) # False

# 字符串运算
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
print(s1 * 3) # HelloHelloHello

输入输出

1
2
3
4
5
6
7
8
# 输入
name = input("请输入你的名字: ")
age = int(input("请输入你的年龄: "))

# 输出
print("你好,", name)
print(f"你今年{age}岁了") # f-string(推荐)
print("你今年{}岁了".format(age)) # format方法

4. 数据结构

字符串(String)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 字符串创建
s = "Hello, Python!"

# 字符串方法
print(s.lower()) # 转小写
print(s.upper()) # 转大写
print(s.title()) # 单词首字母大写
print(s.strip()) # 去除两端空格
print(s.replace("Python", "World")) # 替换
print(s.split(",")) # 分割字符串
print(",".join(["a", "b", "c"])) # 连接字符串

# 字符串索引和切片
print(s[0]) # H
print(s[7:13]) # Python
print(s[-7:-1]) # Python
print(s[::-1]) # 反转字符串

# 字符串格式化
name = "Alice"
age = 25
print(f"姓名: {name}, 年龄: {age}")
print("姓名: {}, 年龄: {}".format(name, age))

列表(List)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 列表创建
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 列表操作
fruits.append("grape") # 添加元素
fruits.insert(1, "pear") # 插入元素
fruits.remove("banana") # 删除元素
popped = fruits.pop() # 弹出最后一个元素
fruits.sort() # 排序
fruits.reverse() # 反转

# 列表切片
print(numbers[1:3]) # [2, 3]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
print(numbers[::2]) # [1, 3, 5]

# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

元组(Tuple)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 元组创建(不可变)
coordinates = (10, 20)
person = ("Alice", 25, "Engineer")
single_tuple = (5,) # 单元素元组需要逗号

# 元组操作
print(coordinates[0]) # 10
print(coordinates[1]) # 20
x, y = coordinates # 解包
print(len(coordinates)) # 长度

# 元组 vs 列表
# 元组不可变,更安全,性能更好
# 列表可变,功能更丰富

字典(Dictionary)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 字典创建
person = {
"name": "Alice",
"age": 25,
"city": "Beijing"
}

# 字典操作
print(person["name"]) # 访问
person["job"] = "Engineer" # 添加/修改
del person["city"] # 删除
print(person.get("age")) # 安全访问
print("name" in person) # 检查键是否存在

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

# 字典推导式
squares = {x: x**2 for x in range(5)}

集合(Set)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 集合创建(无序、不重复)
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 4, 5])

# 集合操作
fruits.add("grape") # 添加元素
fruits.remove("banana") # 删除元素

# 集合运算
set1 = {1, 2, 3}
set2 = {2, 3, 4}

print(set1 | set2) # 并集 {1, 2, 3, 4}
print(set1 & set2) # 交集 {2, 3}
print(set1 - set2) # 差集 {1}
print(set1 ^ set2) # 对称差集 {1, 4}

5. 控制流程

条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# if-elif-else
age = 18

if age < 13:
print("儿童")
elif age < 18:
print("青少年")
elif age < 60:
print("成年人")
else:
print("老年人")

# 三元运算符
status = "成年" if age >= 18 else "未成年"
print(status)

# 多重条件
score = 85
if score >= 90 and score <= 100:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"

循环语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# for循环
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
print(fruit)

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

for i in range(1, 6): # 1到5
print(i)

for i in range(0, 10, 2): # 0,2,4,6,8
print(i)

# 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)

枚举和zip

1
2
3
4
5
6
7
8
9
10
# enumerate - 获取索引和值
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

# zip - 同时遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")

6. 函数编程

函数定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 基本函数
def greet():
print("Hello, World!")

# 带参数的函数
def greet_name(name):
print(f"Hello, {name}!")

# 带返回值的函数
def add(a, b):
return a + b

# 调用函数
greet()
greet_name("Alice")
result = add(5, 3)

参数类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 默认参数
def greet(name, message="Hello"):
print(f"{message}, {name}!")

# 关键字参数
greet(message="Hi", name="Bob")

# 可变参数 *args
def sum_all(*numbers):
return sum(numbers)

print(sum_all(1, 2, 3, 4, 5))

# 关键字可变参数 **kwargs
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")

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

函数高级特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 函数作为参数
def apply_operation(x, y, operation):
return operation(x, y)

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

result = apply_operation(5, 3, multiply)

# lambda函数
square = lambda x: x ** 2
result = apply_operation(5, 3, lambda a, b: a + b)

# 闭包
def make_multiplier(n):
def multiplier(x):
return x * n
return multiplier

double = make_multiplier(2)
print(double(5)) # 10

装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 简单装饰器
def my_decorator(func):
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

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

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

greet("Alice")

7. 文件操作

文件读写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, World!\n")
file.write("这是第二行\n")

# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)

# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())

# 读取所有行
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
print(line.strip())

CSV文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import csv

# 写入CSV
with open("data.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["姓名", "年龄", "城市"])
writer.writerow(["Alice", 25, "Beijing"])
writer.writerow(["Bob", 30, "Shanghai"])

# 读取CSV
with open("data.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)

# 字典方式读写CSV
with open("data.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['姓名']} - {row['年龄']} - {row['城市']}")

JSON文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import json

# 数据
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "swimming"],
"address": {
"city": "Beijing",
"street": "Main St"
}
}

# 写入JSON
with open("data.json", "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=2)

# 读取JSON
with open("data.json", "r", encoding="utf-8") as file:
loaded_data = json.load(file)
print(loaded_data)

8. 面向对象编程

类和对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 类定义
class Person:
# 类属性
species = "人类"

# 初始化方法
def __init__(self, name, age):
# 实例属性
self.name = name
self.age = age

# 实例方法
def introduce(self):
return f"我叫{self.name},今年{self.age}岁"

# 类方法
@classmethod
def get_species(cls):
return cls.species

# 静态方法
@staticmethod
def is_adult(age):
return age >= 18

# 创建对象
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# 访问属性和方法
print(person1.name)
print(person1.introduce())
print(Person.get_species())
print(Person.is_adult(20))

继承和多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 父类
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
raise NotImplementedError("子类必须实现此方法")

# 子类
class Dog(Animal):
def speak(self):
return f"{self.name} 说: 汪汪!"

class Cat(Animal):
def speak(self):
return f"{self.name} 说: 喵喵!"

# 多态
def animal_sound(animal):
print(animal.speak())

dog = Dog("旺财")
cat = Cat("咪咪")

animal_sound(dog) # 旺财 说: 汪汪!
animal_sound(cat) # 咪咪 说: 喵喵!

封装和属性控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # 保护属性
self.__account_id = "12345" # 私有属性

# 属性装饰器
@property
def balance(self):
return self._balance

@balance.setter
def balance(self, amount):
if amount < 0:
raise ValueError("余额不能为负")
self._balance = amount

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

# 使用
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
print(account.balance) # 1300

9. 错误和异常处理

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 基本异常处理
try:
number = int(input("请输入一个数字: "))
result = 10 / number
print(f"结果是: {result}")
except ValueError:
print("输入的不是有效数字!")
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生错误: {e}")
else:
print("计算成功!")
finally:
print("程序执行完毕")

# 抛出异常
def validate_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age > 150:
raise ValueError("年龄不能超过150")
return True

try:
validate_age(-5)
except ValueError as e:
print(f"验证失败: {e}")

自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"余额不足。当前余额: {balance}, 需要: {amount}")

class BankAccount:
def __init__(self, balance=0):
self.balance = balance

def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance

# 使用自定义异常
account = BankAccount(100)
try:
account.withdraw(200)
except InsufficientFundsError as e:
print(e)

10. 模块和包

创建和使用模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):
return a - b

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

def divide(a, b):
if b == 0:
raise ValueError("不能除以零")
return a / b

# main.py
import math_operations as mo
from math_operations import add, multiply

print(mo.add(5, 3))
print(add(10, 2))
print(multiply(4, 5))

创建包

1
2
3
4
5
6
7
my_package/
__init__.py
math_ops.py
string_ops.py
utils/
__init__.py
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# my_package/math_ops.py
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# my_package/string_ops.py
def reverse_string(s):
return s[::-1]

def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)

# 使用包
from my_package import math_ops, string_ops

print(math_ops.factorial(5))
print(string_ops.reverse_string("hello"))

常用内置模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import math
import random
import datetime
import os
import sys

# math模块
print(math.sqrt(16))
print(math.pi)
print(math.sin(math.pi/2))

# random模块
print(random.random()) # 0-1随机小数
print(random.randint(1, 10)) # 1-10随机整数
print(random.choice(["a", "b", "c"])) # 随机选择

# datetime模块
now = datetime.datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# os模块
print(os.getcwd()) # 当前工作目录
print(os.listdir(".")) # 列出目录内容

# sys模块
print(sys.version) # Python版本
print(sys.path) # 模块搜索路径

11. 数据科学库

NumPy - 数值计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import numpy as np

# 创建数组
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.zeros((3, 3)) # 3x3零矩阵
arr3 = np.ones((2, 4)) # 2x4一矩阵
arr4 = np.arange(0, 10, 2) # 0到10,步长2

# 数组操作
print(arr1.shape) # 形状
print(arr1.dtype) # 数据类型
print(arr1 + 2) # 广播
print(np.dot(arr1, arr1)) # 点积

# 数组索引和切片
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix[1, 2]) # 第2行第3列
print(matrix[:, 1]) # 第2列

Pandas - 数据分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pandas as pd

# 创建DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 28],
'City': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen'],
'Salary': [50000, 60000, 70000, 55000]
}

df = pd.DataFrame(data)
print(df)

# 数据操作
print(df.head(2)) # 前2行
print(df.describe()) # 描述性统计
print(df[df['Age'] > 28]) # 条件筛选
print(df.groupby('City')['Salary'].mean()) # 分组聚合

# 读取CSV文件
# df = pd.read_csv('data.csv')
# df.to_csv('output.csv', index=False)

Matplotlib - 数据可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import matplotlib.pyplot as plt
import numpy as np

# 线图
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)')
plt.title('正弦函数')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.legend()
plt.grid(True)
plt.show()

# 柱状图
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

plt.figure(figsize=(8, 6))
plt.bar(categories, values, color='skyblue')
plt.title('柱状图示例')
plt.xlabel('类别')
plt.ylabel('数值')
plt.show()

# 散点图
x = np.random.randn(100)
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)

plt.figure(figsize=(8, 6))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5)
plt.title('散点图示例')
plt.xlabel('X')
plt.ylabel('Y')
plt.colorbar()
plt.show()

12. Web开发

Flask Web框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def home():
return '欢迎来到首页!'

@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'

@app.route('/user', methods=['GET', 'POST'])
def user():
if request.method == 'POST':
name = request.form['name']
return f'用户 {name} 已创建!'
return '''
<form method="post">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
'''

@app.route('/api/data')
def api_data():
data = {
'name': 'Alice',
'age': 25,
'city': 'Beijing'
}
return jsonify(data)

if __name__ == '__main__':
app.run(debug=True)

网络请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests

# GET请求
response = requests.get('https://api.github.com/users/octocat')
data = response.json()
print(data['login'], data['public_repos'])

# POST请求
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json())

# 带headers的请求
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get('https://api.github.com/users/octocat', headers=headers)

13. 自动化脚本

文件批量处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
import shutil

# 遍历目录
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
print(f"找到文本文件: {file_path}")

# 批量重命名
def batch_rename(directory, prefix):
for i, filename in enumerate(os.listdir(directory)):
if filename.endswith('.txt'):
new_name = f"{prefix}_{i+1}.txt"
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f"重命名: {filename} -> {new_name}")

# batch_rename('./documents', 'document')

发送邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(to_email, subject, message):
# 配置信息
smtp_server = "smtp.gmail.com"
port = 587
sender_email = "your_email@gmail.com"
password = "your_password"

# 创建邮件
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = to_email
msg['Subject'] = subject

msg.attach(MIMEText(message, 'plain'))

# 发送邮件
try:
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)
text = msg.as_string()
server.sendmail(sender_email, to_email, text)
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
finally:
server.quit()

# send_email("recipient@example.com", "测试邮件", "这是一封测试邮件")

14. 最佳实践

代码风格(PEP 8)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 好的代码风格示例
def calculate_area(length, width):
"""
计算矩形面积

Args:
length (float): 长度
width (float): 宽度

Returns:
float: 面积
"""
if length <= 0 or width <= 0:
raise ValueError("长度和宽度必须为正数")

area = length * width
return area

# 使用类型提示(Python 3.5+)
from typing import List, Dict, Optional

def process_data(
data: List[Dict[str, int]],
threshold: Optional[int] = None
) -> List[Dict[str, int]]:
"""处理数据,过滤掉值小于阈期的项目"""
if threshold is None:
return data

filtered_data = [
item for item in data
if all(value >= threshold for value in item.values())
]
return filtered_data

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import unittest

def add(a, b):
return a + b

class TestMathOperations(unittest.TestCase):

def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)

def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)

def test_add_zero(self):
self.assertEqual(add(5, 0), 5)

def test_add_floats(self):
self.assertAlmostEqual(add(1.1, 2.2), 3.3, places=1)

if __name__ == '__main__':
unittest.main()

虚拟环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 创建虚拟环境
python -m venv myenv

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

# 安装包
pip install requests pandas numpy

# 生成requirements.txt
pip freeze > requirements.txt

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

# 退出虚拟环境
deactivate

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 使用生成器节省内存
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()

# 使用列表推导式
squares = [x**2 for x in range(1000)]

# 使用局部变量
def calculate_sum(numbers):
total = 0
add = total += # 局部变量引用
for num in numbers:
add(num)
return total

# 使用内置函数
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
maximum = max(numbers)

学习资源推荐

官方文档

在线学习平台

实践项目

  1. 计算器应用
  2. 待办事项列表
  3. 网络爬虫
  4. 数据可视化仪表板
  5. 简单的Web应用

进阶学习

  • 《Python编程:从入门到实践》
  • 《流畅的Python》
  • 《Effective Python》

这个Python教程涵盖了从基础到高级的主要知识点。建议按照顺序学习,每个章节都动手实践代码。Python的学习最重要的是多写代码、多解决问题,通过实际项目来巩固所学知识。祝各位学习顺利!