前言

Python 是目前最流行、最易学的编程语言之一。它以语法简洁、可读性强、生态丰富著称,广泛应用于 Web 开发、数据分析、人工智能、自动化脚本等领域。

本文将从零开始,带你系统掌握 Python 的核心基础。

为什么选择 Python?

优势 说明
📖 语法简洁 接近自然语言,代码量通常是 Java/C++ 的 1/3~1/5
🚀 上手极快 无需编译,写完即运行
📦 生态丰富 PyPI 上超过 50 万个第三方包
🎯 应用广泛 Web、爬虫、AI、自动化测试、数据科学
👨‍👩‍👧‍👦 社区活跃 遇到问题容易找到答案

一、环境搭建

1.1 安装 Python

python.org 下载安装。安装时务必勾选 “Add Python to PATH”

Linux 安装:

1
sudo apt install python3 python3-pip

验证安装:

1
2
3
4
5
python3 --version
# Python 3.12.0

pip3 --version
# pip 24.0

1.2 运行 Python 代码

1
2
3
4
5
# 交互式解释器(逐行输入执行)
python3

# 运行 .py 文件
python3 hello.py

二、第一个 Python 程序

1
2
3
# hello.py
print("Hello, 七月小站!")
print("你好,世界!")

运行:

1
2
3
python3 hello.py
# Hello, 七月小站!
# 你好,世界!

三、变量与数据类型

3.1 变量

Python 是动态类型语言,变量无需声明类型:

1
2
3
4
5
6
7
8
9
10
11
12
name = "July"        # 字符串
age = 25 # 整数
height = 1.75 # 浮点数
is_student = False # 布尔值

# 多变量赋值
a, b, c = 1, 2, 3
x = y = z = 100

# 查看类型
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>

3.2 数字类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 整数 int(无限精度)
n1 = 100
n2 = -50
big = 12345678901234567890

# 浮点数 float
pi = 3.14159
e = 2.71828

# 复数 complex
c = 3 + 4j

# 运算
print(10 + 3) # 13 (加)
print(10 - 3) # 7 (减)
print(10 * 3) # 30 (乘)
print(10 / 3) # 3.333... (除,总是返回浮点)
print(10 // 3) # 3 (整除)
print(10 % 3) # 1 (取余)
print(10 ** 3) # 1000 (幂运算)

3.3 字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 三种引号
s1 = '单引号'
s2 = "双引号"
s3 = """可以跨行的
三引号字符串"""

# 拼接
name = "July"
greeting = "你好, " + name
repeat = "Ha" * 3 # HaHaHa
formatted = f"{name},欢迎来到博客!"
print(formatted) # July,欢迎来到博客!

# 常用方法
s = " Hello, Python! "
print(s.strip()) # "Hello, Python!" (去首尾空格)
print(s.upper()) # " HELLO, PYTHON! "
print(s.lower()) # " hello, python! "
print(s.replace("Python", "World"))
print(s.split(",")) # [' Hello', ' Python! ']
print(len(s)) # 长度
print("Py" in s) # True (包含判断)
print(s[3:8]) # "Hello" (切片)

3.4 格式化输出

1
2
3
4
5
6
7
8
9
10
11
12
name = "July"
age = 25
score = 99.5

# f-string(最推荐,Python 3.6+)
print(f"我是{name},今年{age}岁,成绩{score}分")

# format 方法
print("我是{},今年{}岁,成绩{:.1f}分".format(name, age, score))

# % 格式化(旧式)
print("我是%s,今年%d岁,成绩%.1f分" % (name, age, score))

四、常用数据结构

4.1 列表(list)— 有序可变序列

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
# 创建
fruits = ["苹果", "香蕉", "橘子", "草莓"]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4]]
empty = []
dup = [0] * 5 # [0, 0, 0, 0, 0]

# 访问
print(fruits[0]) # 苹果(第一个)
print(fruits[-1]) # 草莓(最后一个)
print(fruits[1:3]) # ['香蕉', '橘子'](切片)

# 修改
fruits[0] = "芒果"
fruits.append("葡萄") # 末尾追加
fruits.insert(1, "西瓜") # 指定位置插入
fruits.extend(["樱桃", "榴莲"]) # 扩展

# 删除
fruits.remove("香蕉") # 按值删除
popped = fruits.pop() # 弹出最后一个
popped = fruits.pop(0) # 弹出指定位置
del fruits[2] # 删除指定位置
fruits.clear() # 清空

# 遍历
for fruit in fruits:
print(fruit, end=" ")

# 带索引遍历
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")

# 列表推导式(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]
pairs = [(x, y) for x in range(2) for y in range(2)]

# 常用操作
print(len(fruits)) # 长度
print("苹果" in fruits) # 是否存在
fruits.sort() # 原地排序
fruits.sort(reverse=True) # 降序
sorted_list = sorted(fruits) # 返回新排序列表
fruits.reverse() # 反转

4.2 元组(tuple)— 有序不可变序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 创建
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # 单元素元组必须有逗号!
empty = ()

# 用途
x, y = point # 解包
a, b = b, a # 优雅地交换两个变量
coords = [(1, 2), (3, 4)] # 常用于结构化数据

# 元组不可修改,但可以包含可变对象
t = ([1, 2], 3)
t[0].append(3) # 可以的,因为列表本身可变
# t[0] = [4, 5] # 不行!元组元素不可重新赋值

4.3 字典(dict)— 键值对 ⭐

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
# 创建
person = {
"name": "July",
"age": 25,
"city": "深圳",
"hobbies": ["编程", "阅读", "摄影"]
}
empty_dict = {}
numbered = dict(a=1, b=2, c=3)

# 增删改查
person["email"] = "july@example.com" # 增
person["age"] = 26 # 改
del person["city"] # 删
person.pop("email") # 删并返回值
name = person["name"] # 查(key 不存在会报错)
name = person.get("name", "匿名") # 查(key 不存在返回默认值)

# 安全访问嵌套值
data = {"user": {"profile": {"name": "July"}}}
print(data.get("user", {}).get("profile", {}).get("name"))

# 遍历
for key in person:
print(f"{key}: {person[key]}")

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

# 检查
if "name" in person:
print("name 存在")

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

# 合并字典(Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b # {'x': 1, 'y': 3, 'z': 4}(键冲突时右侧优先)

常用字典场景 — 统计词频:

1
2
3
4
5
6
text = "hello world hello python world world"
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq) # {'hello': 2, 'world': 3, 'python': 1}

4.4 集合(set)— 无序不重复集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 创建
s = {1, 2, 3, 4, 5}
empty_set = set() # 不能用 {},那是空字典

# 去重
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums)) # [1, 2, 3, 4]

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b) # 并集: {1, 2, 3, 4, 5, 6}
print(a & b) # 交集: {3, 4}
print(a - b) # 差集: {1, 2}
print(a ^ b) # 对称差: {1, 2, 5, 6}

# 增删
s.add(6)
s.remove(1) # 不存在则报错
s.discard(10) # 不存在也不报错(推荐)

五、流程控制

5.1 if / elif / else

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

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

print(f"成绩等级: {grade}")

# 三元表达式
status = "成年" if age >= 18 else "未成年"

# 条件链式比较
x = 10
if 0 < x < 20:
print("x 在 0 到 20 之间")

5.2 for 循环

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
# 遍历列表
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(f"我喜欢{fruit}")

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

for i in range(2, 8): # 2 3 4 5 6 7
print(i)

for i in range(1, 10, 2): # 1 3 5 7 9(步长为 2)
print(i)

# 倒序
for i in range(10, 0, -1):
print(i)

# else 子句(没有被 break 中断时执行)
for i in range(5):
if i == 100:
break
else:
print("循环正常结束,没有被中断")

5.3 while 循环

1
2
3
4
5
6
7
8
9
10
11
count = 0
while count < 5:
print(count)
count += 1

# 无限循环 + break
while True:
user_input = input("输入 q 退出: ")
if user_input == "q":
break
print(f"你输入了: {user_input}")

5.4 break / continue

1
2
3
4
5
6
7
8
9
10
11
# break:跳出循环
for i in range(10):
if i == 5:
break
print(i) # 0 1 2 3 4

# continue:跳过本次迭代
for i in range(5):
if i == 2:
continue
print(i) # 0 1 3 4

六、函数

6.1 基本函数

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
# 定义函数
def greet(name):
"""向指定的人打招呼(文档字符串)"""
return f"你好,{name}!"

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

# 默认参数
def power(x, n=2):
return x ** n

# 关键字参数
print(power(n=3, x=2)) # 8

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

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

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

info(name="July", age=25, city="深圳")

# 类型提示(Python 3.5+,可选的提示)
def calculate(price: float, quantity: int) -> float:
return price * quantity

6.2 Lambda 表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 简单的一行函数
square = lambda x: x ** 2
print(square(5)) # 25

# 配合高阶函数使用
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

# 配合 sorted 自定义排序
students = [
{"name": "张三", "score": 85},
{"name": "李四", "score": 92},
{"name": "王五", "score": 78},
]
# 按分数降序排序
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)

6.3 作用域规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# LEGB 规则:Local → Enclosing → Global → Built-in

x = "global"

def outer():
x = "enclosing"

def inner():
x = "local"
print(x) # local(就近原则)

inner()

outer()
print(x) # global

七、面向对象编程(OOP)

7.1 类与对象

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
class User:
"""用户类"""

# 类属性(所有实例共享)
count = 0

# 构造方法
def __init__(self, username, email, age=18):
self.username = username # 实例属性
self.email = email
self._age = age # 单下划线:约定为"受保护的"
self.__password = "123456" # 双下划线:名称修饰为 _User__password
User.count += 1

# 实例方法
def greet(self):
return f"你好,我是{self.username}"

# 属性访问器(getter)
@property
def age(self):
return self._age

# 属性设置器(setter)
@age.setter
def age(self, value):
if value < 0:
raise ValueError("年龄不能为负")
self._age = value

# 类方法
@classmethod
def get_count(cls):
return cls.count

# 静态方法
@staticmethod
def validate_email(email):
return "@" in email and "." in email

# 字符串表示
def __str__(self):
return f"User({self.username})"

def __repr__(self):
return f"User(username='{self.username}', email='{self.email}')"

# 使用
user1 = User("july", "july@example.com", 25)
user2 = User("zhangsan", "zhangsan@example.com")

print(user1.greet()) # 你好,我是july
print(User.count) # 2
print(User.validate_email("test@x")) # True
print(user1.age) # 25
user1.age = 26 # 调用 setter
# user1.age = -5 # 抛出 ValueError

7.2 继承

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
# 基类
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "..."

# 派生类
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 调用父类构造
self.breed = breed

def speak(self):
return "汪汪汪!"

class Cat(Animal):
def speak(self):
return "喵喵喵!"

# 多态
animals = [Dog("旺财", "金毛"), Cat("小花")]
for animal in animals:
print(f"{animal.name} 说: {animal.speak()}")

# 多重继承
class Flyable:
def fly(self):
return "飞起来了"

class Swimmable:
def swim(self):
return "游起来了"

class Duck(Animal, Flyable, Swimmable):
def speak(self):
return "嘎嘎嘎!"

duck = Duck("唐老鸭")
print(duck.fly()) # 飞起来了
print(duck.swim()) # 游起来了

八、异常处理

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
# 基本结构
try:
num = int(input("请输入一个数字: "))
result = 10 / num
print(f"10 / {num} = {result}")
except ValueError:
print("请输入有效的数字!")
except ZeroDivisionError:
print("除数不能为零!")
except Exception as e:
print(f"发生未知错误: {e}")
else:
print("执行成功!") # 没有异常时执行
finally:
print("无论是否异常都会执行") # 清理资源

# 自定义异常
class InvalidAgeError(Exception):
def __init__(self, age):
self.age = age
super().__init__(f"无效的年龄: {age}")

def set_age(age):
if age < 0 or age > 150:
raise InvalidAgeError(age)
print(f"年龄设置为 {age}")

# 使用上下文管理器 with(自动处理资源)
# 等价于 try-finally
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# 文件会自动关闭,即使发生异常

九、文件操作

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
# ===== 读取文件 =====
# 一次性读取所有内容
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()

# 逐行读取(适合大文件)
with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())

# 读取所有行到列表
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()

# ===== 写入文件 =====
# 覆盖写入
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("第二行内容\n")

# 追加写入
with open("output.txt", "a", encoding="utf-8") as f:
f.write("追加的一行\n")

# 一次性写入多行
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines)

# ===== 文件模式 =====
# r 只读(默认)
# w 写入(覆盖)
# a 追加
# x 创建(文件存在则报错)
# b 二进制模式
# + 读写
# r+ 读写,指针在开头
# w+ 读写,先清空文件

JSON 操作

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

# 写入 JSON
data = {
"name": "July",
"age": 25,
"hobbies": ["编程", "阅读"]
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)

# 读取 JSON
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])

# JSON 字符串 ↔ 字典
json_str = json.dumps(data, ensure_ascii=False)
data_back = json.loads(json_str)

CSV 操作

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

# 写入 CSV
with open("users.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "年龄", "城市"])
writer.writerow(["张三", 25, "北京"])
writer.writerow(["李四", 30, "上海"])

# 读取 CSV
with open("users.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['姓名']}, {row['年龄']}岁")

十、常用标准库

10.1 os — 操作系统接口

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
import os

# 路径操作
print(os.getcwd()) # 当前工作目录
os.chdir("/tmp") # 切换目录
os.listdir(".") # 列出目录内容

# 文件操作
os.mkdir("new_folder") # 创建目录
os.makedirs("a/b/c") # 递归创建目录
os.remove("file.txt") # 删除文件
os.rmdir("empty_folder") # 删除空目录
os.rename("old.txt", "new.txt") # 重命名

# 路径拼接(跨平台)
path = os.path.join("dir", "subdir", "file.txt")
print(os.path.exists(path)) # 路径是否存在
print(os.path.isfile(path)) # 是否是文件
print(os.path.isdir(path)) # 是否是目录
dir_part, file_part = os.path.split(path)
name, ext = os.path.splitext("data.txt") # ('data', '.txt')

# 环境变量
print(os.environ.get("HOME"))
os.environ["MY_VAR"] = "hello"

10.2 sys — 系统相关

1
2
3
4
5
6
7
8
9
10
import sys

print(sys.version) # Python 版本
print(sys.argv) # 命令行参数
print(sys.platform) # 操作系统平台

# 命令行参数示例
# python3 script.py --name July --age 25
if len(sys.argv) > 1:
print(f"参数: {sys.argv[1:]}")

10.3 datetime — 日期时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from datetime import datetime, date, timedelta

# 当前时间
now = datetime.now()
print(now) # 2026-05-30 17:00:00.123456
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化输出

# 日期解析
birthday = datetime.strptime("2000-01-01", "%Y-%m-%d")

# 时间运算
tomorrow = now + timedelta(days=1)
yesterday = now - timedelta(days=1)
one_hour_later = now + timedelta(hours=1)
diff = now - birthday # timedelta 对象
print(f"已出生 {diff.days} 天")

# 常用快捷操作
today = date.today()
print(today.year, today.month, today.day)

常用日期格式符:

符号 含义 示例
%Y 四位年份 2026
%m 月份(01-12) 05
%d 日期(01-31) 30
%H 小时(00-23) 17
%M 分钟(00-59) 30
%S 秒(00-59) 45

10.4 random — 随机数

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

print(random.random()) # 0~1 的浮点数
print(random.randint(1, 100)) # 1~100 的整数
print(random.choice(["A", "B", "C", "D"])) # 随机选一个
print(random.sample(range(100), 5)) # 不重复选 5 个

# 随机打乱
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)

# 随机字符串
import string
chars = string.ascii_letters + string.digits
password = "".join(random.choices(chars, k=16))
print(f"随机密码: {password}")

10.5 re — 正则表达式

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
import re

text = "联系方式: july@example.com, 电话: 13800138000"

# 搜索
match = re.search(r"(\w+)@(\w+\.\w+)", text)
if match:
print(f"邮箱: {match.group()}") # july@example.com
print(f"用户名: {match.group(1)}") # july
print(f"域名: {match.group(2)}") # example.com

# 查找所有匹配
phone_numbers = re.findall(r"\d{11}", text)
print(phone_numbers) # ['13800138000']

# 替换
censored = re.sub(r"\d{11}", "***", text)
print(censored)

# 常用模式
# \d 数字 \w 字母/数字/下划线
# \s 空白 . 任意字符
# * 0或多次 + 1或多次
# ? 0或1次 {n} n次
# ^ 开头 $ 结尾

十一、第三方库安装

1
2
3
4
5
6
7
8
9
10
11
12
13
# 安装第三方库
pip install requests
pip install pandas
pip install flask

# 查看已安装的库
pip list

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

# 导出当前环境依赖
pip freeze > requirements.txt

requests — HTTP 请求

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
import requests

# GET 请求
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code) # 200
user_data = response.json()
print(user_data["login"]) # octocat

# POST 请求
data = {"title": "文章标题", "content": "文章内容"}
resp = requests.post("https://httpbin.org/post", json=data)
print(resp.json())

# 带请求头和参数
headers = {"Authorization": "Bearer token123"}
params = {"page": 1, "size": 10}
resp = requests.get("https://api.example.com/users",
headers=headers, params=params)

# 超时和异常处理
try:
resp = requests.get("https://example.com", timeout=5)
resp.raise_for_status() # 非 200 状态码抛出异常
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")

十二、实战:Todo 命令行应用

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
#!/usr/bin/env python3
"""简易 Todo 应用"""

import json
import sys
from datetime import datetime

TODO_FILE = "todos.json"

def load_todos():
try:
with open(TODO_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return []

def save_todos(todos):
with open(TODO_FILE, "w", encoding="utf-8") as f:
json.dump(todos, f, ensure_ascii=False, indent=2)

def list_todos(todos):
if not todos:
print("暂无待办事项 🎉")
return
print("\n===== 待办列表 =====")
for i, todo in enumerate(todos, 1):
status = "✅" if todo["done"] else "⬜"
print(f" {status} {i}. {todo['title']} ({todo['created']})")
print()

def add_todo(todos, title):
todos.append({
"title": title,
"done": False,
"created": datetime.now().strftime("%Y-%m-%d %H:%M")
})
save_todos(todos)
print(f"✅ 已添加: {title}")

def mark_done(todos, index):
if 0 <= index < len(todos):
todos[index]["done"] = True
save_todos(todos)
print(f"✅ 已完成: {todos[index]['title']}")

def delete_todo(todos, index):
if 0 <= index < len(todos):
title = todos[index]["title"]
todos.pop(index)
save_todos(todos)
print(f"🗑️ 已删除: {title}")

def main():
todos = load_todos()

if len(sys.argv) < 2:
list_todos(todos)
print("用法: python3 todo.py [add|done|del|list] [参数]")
return

command = sys.argv[1]

if command == "add":
title = " ".join(sys.argv[2:]) if len(sys.argv) > 2 else input("标题: ")
add_todo(todos, title)
elif command == "done":
index = int(sys.argv[2]) - 1
mark_done(todos, index)
elif command == "del":
index = int(sys.argv[2]) - 1
delete_todo(todos, index)
elif command == "list":
list_todos(todos)
else:
print(f"未知命令: {command}")

if __name__ == "__main__":
main()

使用演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
python3 todo.py add "买水果"
# ✅ 已添加: 买水果

python3 todo.py add "完成博客文章"
# ✅ 已添加: 完成博客文章

python3 todo.py list
# ===== 待办列表 =====
# ⬜ 1. 买水果 (2026-05-30 17:00)
# ⬜ 2. 完成博客文章 (2026-05-30 17:01)

python3 todo.py done 1
# ✅ 已完成: 买水果

常用 Python 命令速查

命令 说明
python3 file.py 运行 Python 脚本
python3 -c "code" 执行一行代码
python3 -m module 以模块方式运行
python3 -m http.server 8000 启动简易 HTTP 服务器
python3 -m venv venv 创建虚拟环境
source venv/bin/activate 激活虚拟环境
deactivate 退出虚拟环境
pip install pkg 安装包
pip uninstall pkg 卸载包
pip list 列出已安装包

进一步学习

  1. Web 框架:Flask(轻量)、Django(全栈)、FastAPI(高性能)
  2. 数据科学三剑客:NumPy + Pandas + Matplotlib
  3. 爬虫:requests + BeautifulSoup + Scrapy
  4. 自动化:Selenium、pyautogui、schedule
  5. 虚拟环境:venv / Poetry(依赖管理和打包)

结语

Python 的哲学是”优雅、明确、简单”(import this 可查看 Python 之禅)。它可能是最适合初学者的编程语言,同时功能也足够强大来支撑工业级项目。

本文涵盖了 Python 开发中最核心的基础知识。最重要的一步:打开终端,敲下 python3,把每个示例都亲手跑一遍!

Life is short, you need Python. 🐍