开胃菜与安装

翻译整理自 Python Tutorial - Whetting Your Appetite 与 Using Python on Windows。

1. Python 是什么

Python 是一门解释型、面向对象、动态类型的高级编程语言。它内建高级数据结构(list、dict、set),提供动态类型与动态绑定,以及完整的标准库。

设计哲学(PEP 20 - The Zen of Python):

Simple is better than complex. Beautiful is better than ugly. Readability counts.

在 REPL 中输入 import this 可以看到完整内容。

2. 安装 Python

前往 https://www.python.org/downloads/ 下载最新稳定版(3.12+):

  • Windows:运行安装包,勾选 Add Python to PATH,再选 Install Now
  • macOS:使用 brew install python 或官网 pkg
  • Linux:发行版自带或 apt install python3,新版本可用 pyenv

验证:

python --version
# Python 3.12.3

python -m pip --version

3. 第一个程序 Hello World

新建 hello.py:

print("Hello, World!")

运行:

python hello.py
# Hello, World!

print() 是内置函数,自动在结尾换行;可通过 end="" 关闭。

4. 源代码字符编码

Python 3 默认源文件编码为 UTF-8,可以直接在源码中使用中文:

# -*- coding: utf-8 -*-
greeting = "你好,世界"
print(greeting)

5. 启动解释器

python   # 进入交互模式
>>> 1 + 1
2
>>> exit()

也可以使用更友好的 REPL:

  • ipython:补全、魔法命令
  • ptpython:语法高亮、多行编辑
  • bpython:内联文档

6. 运行 Python 脚本的几种方式

python script.py           # 执行脚本
python -m module           # 以模块方式执行
python -c "print('hi')"    # 命令行直接执行
python -i script.py        # 执行后进入交互模式

小结

到这里,你已经完成 Python 安装与第一个程序。下一章学习如何高效使用交互式解释器。