Skip to content

运行第一段程序:环境、解释器与脚本 ​

你要学会什么 ​

第一次学习 Python,先把程序跑起来。理解交互式解释器和脚本文件的区别,知道如何查看版本,观察程序输出。已有编程经验的读者可以快速确认环境,再进入后续机制讲解。

安装与确认 ​

Python 3 通常预装在 macOS 和 Linux 系统中。Windows 用户需要从 python.org 下载安装包。

检查已安装的版本:

bash
python3 --version

预期输出类似:

text
Python 3.12.5

如果显示 Python 2.x.x 或命令不存在,需要安装 Python 3.12 或更高版本。本书使用 Python 3.12 作为基线环境,3.13+ 的新特性会单独标注。

查看 Python 安装位置:

bash
which python3

macOS 输出示例:

text
/usr/bin/python3

交互式解释器:立即反馈 ​

启动 Python 交互式环境(REPL - Read-Eval-Print Loop):

bash
python3

进入后会看到提示符 >>>:

python
Python 3.12.5 (main, Aug  6 2024, 19:23:12) [Clang 15.0.0] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

尝试第一个表达式:

python
>>> 2 + 2
4
>>> print("Hello, Python")
Hello, Python
>>> 50 - 5 * 6
20

解释器立即计算表达式并显示结果。print() 函数用于输出文本。算术运算遵循标准优先级:乘法先于加减法。

退出解释器:

python
>>> exit()

或按 Ctrl+D(Unix/macOS)、Ctrl+Z 然后回车(Windows)。

脚本文件:可重复运行 ​

交互式环境适合快速实验,但不能保存代码。真实程序使用脚本文件。

创建文件 hello.py:

python
# 这是注释,解释器会忽略它
print("Hello from a script")

# 简单计算
width = 20
height = 5 * 9
print(f"Area: {width * height}")

运行脚本:

bash
python3 hello.py

预期输出:

text
Hello from a script
Area: 900

注意事项:

  • Python 文件扩展名是 .py
  • 注释以 # 开头,延伸到行尾
  • 脚本可以包含多条语句,按顺序执行
  • f"..." 是格式化字符串(f-string),{} 内的表达式会被求值

缩进与语法 ​

Python 使用缩进表示代码块,不用大括号:

python
x = 10
if x > 5:
    print("x 大于 5")
    print("这也在 if 块内")
print("这在 if 块外")

将此代码保存为 indent_demo.py 并运行:

bash
python3 indent_demo.py

输出:

text
x 大于 5
这也在 if 块内
这在 if 块外

关键规则:

  • 同一代码块内的语句必须使用相同缩进(通常是 4 个空格)
  • 不要混用空格和制表符
  • 缩进错误会导致 IndentationError

环境变量与路径 ​

Python 解释器通过 PATH 环境变量找到可执行文件。检查 Python 可执行文件的实际路径:

bash
python3 -c "import sys; print(sys.executable)"

这会输出解释器二进制文件的完整路径。

查看 Python 搜索模块的路径:

python
>>> import sys
>>> sys.path
['', '/usr/lib/python312.zip', '/usr/lib/python3.12', ...]

sys.path 列出 Python 查找导入模块的目录。第一个空字符串 '' 表示当前目录。

虚拟环境预览 ​

真实项目通常使用虚拟环境隔离依赖。快速体验:

bash
python3 -m venv myenv
source myenv/bin/activate  # Windows: myenv\Scripts\activate
python --version
deactivate

激活虚拟环境后,python 命令指向虚拟环境中的解释器。第十章会详细讲解依赖管理和虚拟环境。

常见问题 ​

python vs python3?

某些系统中 python 仍指向 Python 2.x。始终使用 python3 确保运行 Python 3。虚拟环境激活后可以直接用 python。

脚本不执行?

检查文件名拼写、当前目录、文件权限。使用 ls -l hello.py(Unix)或 dir hello.py(Windows)确认文件存在。

SyntaxError 或 IndentationError?

检查引号配对、括号匹配、缩进一致性。Python 错误消息通常会指出问题行号。

练习 ​

  1. 版本确认:运行 python3 --version 并记录输出。如果版本低于 3.10,建议升级。

  2. 交互式计算:启动解释器,计算 (100 - 32) * 5 / 9(华氏度转摄氏度),观察结果是整数还是浮点数。

  3. 第一个脚本:创建 greet.py,包含:

    python
    name = "Alice"
    age = 30
    print(f"{name} is {age} years old")

    运行并观察输出。修改 name 和 age,重新运行。

  4. 观察缩进错误:创建 bad_indent.py:

    python
    x = 5
    if x > 0:
    print("positive")

    运行,观察 IndentationError。修正后重新运行。

完成练习后,打开本章答案页核对。

下一步 ​

环境确认完成。下一节学习值与类型:Python 中的一切都是对象,名字如何绑定到对象,以及对象的身份、类型和值的区别。

回到第一章概览 · 返回Python 学习路线

用心记录每一步成长