Skip to content

L1 — Hello Python

本节目标:掌握 print、变量、注释、模块导入,理解嵌套拆包语法。


基础概念

1. print 输出

Python
print("Hello world!")
print(1 + 2)
Click Run to see output

运行结果:

  • Hello world!
  • 3

2. 变量赋值

Python
name = "Python"
age = 18
is_student = True
print(f"我叫{name},今年{age}岁")
Click Run to see output

3. 注释

Python
# 这是单行注释
"""
这是多行注释,
通常用于文档字符串
"""
Click Run to see output

🎯 理解嵌套拆包:从 MNIST 数据加载说起

目标代码

Python
from mnist.data import load_data
(train_images, train_labels), (test_images, test_labels) = load_data()
Click Run to see output

多文件模块结构

examples/
└── mnist/
    ├── __init__.py       # 包入口(可省略)
    ├── data.py           # 定义 load_data()
    └── main.py           # 导入并使用

data.py — 定义数据加载函数:

Python
def load_data():
    return (训练集图片, 训练集标签), (测试集图片, 测试集标签)
Click Run to see output

main.py — 导入并拆包:

Python
from mnist.data import load_data
(train_images, train_labels), (test_images, test_labels) = load_data()
Click Run to see output

嵌套拆包语法拆解

Python
# load_data() 返回的是嵌套元组:
((train_images, train_labels), (test_images, test_labels))

# 左侧有两层括号 → 对应两层拆包
(train_images, train_labels), (test_images, test_labels) = ...
          ↑ 第一层                    ↑ 第一层
            ↑ 第二层                      ↑ 第二层
Click Run to see output

等价的逐步写法

Python
# 原始返回值
result = load_data()
# result = ((train_images, train_labels), (test_images, test_labels))

# 外层拆包:分出训练集和测试集
train_set, test_set = result

# 内层拆包:分出图片和标签
train_images, train_labels = train_set
test_images, test_labels = test_set
Click Run to see output

Python 模块导入语法

场景语法示例
导入模块import 模块名import mnist
从模块导入函数from 模块 import 函数from mnist.data import load_data
导入并改名from 模块 import 函数 as 别名from mnist.data import load_data as ld
导入多个from 模块 import a, bfrom mnist.data import a, b
相对导入(包内)from . import siblingfrom . import data

对比 Python 内置数据类型

语法类型类比
(a, b)元组(不可变)固定顺序的容器
[a, b]列表(可变)随时可变的容器
{a, b}集合无序、去重
{'x': a}字典键值对

练习

Python
# 1. 尝试用一个变量接住整个返回值,打印它的结构
data = load_data()
print("整体结构:", type(data))
print("第1个元素(训练集):", data[0])
print("第2个元素(测试集):", data[1])

# 2. 用拆包语法赋值
# (train_images, train_labels), (test_images, test_labels) = load_data()
Click Run to see output

⚠️ 本教程使用 Pyodide(浏览器端 Python),不支持 tensorflownumpy 等 C 扩展库。MNIST 示例使用纯 Python 模拟返回值结构。


⚠️ L2 数据类型 — 敬请期待