Python 入门手册——从安装到 Web 开发

Python 入门手册——从安装到 Web 开发

作者: CaoZH
日期: 2024-06-15
本文为原创教程


Python 连续多年在 TIOBE 指数排名前三,在 AI、数据处理、Web 开发、自动化运维等领域都有广泛应用。2024 年,Python 3.12 已经是稳定版本。

本文从零开始,带你入门 Python 编程并搭建一个简单的 Web 应用。

一、安装 Python

1
2
3
4
5
6
7
8
9
10
11
12
13
# Ubuntu/Debian
sudo apt update
sudo apt install -y python3 python3-pip python3-venv

# macOS
brew install python@3.12

# Windows
# 从 https://python.org 下载安装包

# 验证安装
python3 --version # Python 3.12.x
pip3 --version

二、基础语法速览

变量与类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 动态类型,不需要声明类型
name = "张三" # str
age = 28 # int
height = 1.75 # float
is_student = False # bool
hobbies = ["读书", "跑步", "编码"] # list
person = {"name": "李四", "age": 30} # dict

# 类型转换
str(123) # "123"
int("456") # 456
float("3.14") # 3.14

# 字符串操作
name = "Python"
print(name[0]) # P
print(name[-1]) # n
print(name[1:3]) # yt
print(f"Hello {name}!") # f-string,最推荐的格式化方式

流程控制

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
# if-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"

# for 循环
for i in range(5):
print(i) # 0 1 2 3 4

for idx, item in enumerate(hobbies):
print(f"{idx}: {item}")

# while 循环
count = 0
while count < 3:
print(count)
count += 1

# 列表推导式(Python 特色)
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 基本函数
def greet(name: str) -> str:
"""给用户打招呼"""
return f"你好,{name}!"

# 默认参数
def create_user(name, age=18, city="未知"):
return {"name": name, "age": age, "city": city}

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

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

# Lambda 匿名函数
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers)) # [2, 4, 6, 8, 10]

三、文件与异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 读取文件(推荐使用 with 语句)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # 全部读取
lines = f.readlines() # 按行读取

# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!")

# 异常处理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除数不能为零: {e}")
except Exception as e:
print(f"其他错误: {e}")
finally:
print("无论如何都会执行")

四、实战:用 Flask 搭建 Web API

安装 Flask

1
2
3
4
5
6
7
8
# 创建虚拟环境(强烈推荐)
mkdir my-web-app && cd my-web-app
python3 -m venv venv
source venv/bin/activate # Linux/Mac
# venv\Scripts\activate # Windows

# 安装依赖
pip install flask

创建应用

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# app.py
from flask import Flask, request, jsonify
from datetime import datetime

app = Flask(__name__)

# 模拟数据库
users = []
next_id = 1

# 首页
@app.route('/')
def home():
return jsonify({
"message": "Welcome to Python API",
"version": "1.0.0",
"endpoints": {
"GET /users": "获取用户列表",
"GET /users/<id>": "获取单个用户",
"POST /users": "创建用户",
"PUT /users/<id>": "更新用户",
"DELETE /users/<id>": "删除用户"
}
})

# 获取用户列表
@app.route('/users', methods=['GET'])
def get_users():
return jsonify({
"code": 200,
"data": users,
"total": len(users)
})

# 获取单个用户
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user is None:
return jsonify({"code": 404, "message": "用户不存在"}), 404
return jsonify({"code": 200, "data": user})

# 创建用户
@app.route('/users', methods=['POST'])
def create_user():
global next_id
data = request.get_json()

if not data or not data.get('name'):
return jsonify({"code": 400, "message": "缺少必要字段 name"}), 400

user = {
"id": next_id,
"name": data['name'],
"email": data.get('email', ''),
"age": data.get('age', 0),
"created_at": datetime.now().isoformat()
}
next_id += 1
users.append(user)

return jsonify({"code": 200, "message": "创建成功", "data": user}), 201

# 更新用户
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user is None:
return jsonify({"code": 404, "message": "用户不存在"}), 404

data = request.get_json()
user['name'] = data.get('name', user['name'])
user['email'] = data.get('email', user['email'])
user['age'] = data.get('age', user['age'])

return jsonify({"code": 200, "message": "更新成功", "data": user})

# 删除用户
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
global users
user = next((u for u in users if u['id'] == user_id), None)
if user is None:
return jsonify({"code": 404, "message": "用户不存在"}), 404

users = [u for u in users if u['id'] != user_id]
return jsonify({"code": 200, "message": "删除成功"})

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

运行与测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 启动
python app.py
# 输出:Running on http://127.0.0.1:5000

# 测试 API
curl http://localhost:5000/

curl -X POST http://localhost:5000/users \
-H "Content-Type: application/json" \
-d '{"name":"张三","email":"zhangsan@test.com","age":28}'

curl http://localhost:5000/users

curl -X PUT http://localhost:5000/users/1 \
-H "Content-Type: application/json" \
-d '{"age":29}'

curl -X DELETE http://localhost:5000/users/1

五、常用标准库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# os — 操作系统接口
import os
os.getcwd() # 当前目录
os.listdir('.') # 列出文件
os.environ.get('HOME') # 环境变量

# json — JSON 处理
import json
data = {"name": "Python", "version": 3.12}
json_str = json.dumps(data, ensure_ascii=False)
obj = json.loads(json_str)

# datetime — 日期时间
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
formatted = now.strftime("%Y-%m-%d %H:%M:%S")

# re — 正则表达式
import re
pattern = r'\d+'
result = re.findall(pattern, "abc123def456") # ['123', '456']

六、包管理

1
2
3
4
5
6
7
# pip 基本命令
pip install requests # 安装包
pip install flask==3.0.0 # 指定版本
pip uninstall requests # 卸载
pip list # 列出已安装
pip freeze > requirements.txt # 导出依赖
pip install -r requirements.txt # 安装依赖

七、总结

通过本教程,你学会了:

内容 掌握程度
✅ Python 基础语法 变量、类型、流程控制
✅ 函数与模块 函数定义、参数、标准库
✅ 文件与异常 文件读写、异常处理
✅ Flask Web 开发 RESTful API 构建
✅ 包管理 pip、虚拟环境

首发于 CaoZH 的笔记