第 1 章 Python 概述与环境搭建
1.1 Python 的历史与设计哲学
Python 由荷兰程序员 Guido van Rossum 于 1989 年底开始开发,1991 年发布第一个公开版本。名字来源于英国喜剧团体 Monty Python,而非蟒蛇。
Python 的设计哲学被浓缩在一首”诗”里,在解释器中输入即可查看:
import this
输出(节选核心原则):
Beautiful is better than ugly. # 优美胜于丑陋
Explicit is better than implicit. # 明确胜于隐晦
Simple is better than complex. # 简单胜于复杂
Complex is better than complicated. # 复杂胜于凌乱
Readability counts. # 可读性很重要
There should be one-- and preferably only one --obvious way to do it.
# 应该有一种——最好只有一种——明显的方法来做这件事
这些原则深刻影响了 Python 的语法设计。当你犹豫该如何写代码时,回头看看这些原则往往能找到答案。
Python 的核心特点:
- 解释型语言:源码先编译为字节码,再由虚拟机解释执行
- 动态类型:变量不需要声明类型,运行时确定
- 强类型:不允许隐式的类型混合运算(
"3" + 5会报错,不像 JavaScript) - 自动内存管理:引用计数 + 分代垃圾回收
- 缩进即语法:用缩进代替花括号,强制代码格式统一
1.2 Python 2 vs Python 3
Python 3 于 2008 年发布,与 Python 2 不完全兼容。Python 2 已于 2020 年 1 月 1 日正式停止维护。
| 特性 | Python 2 | Python 3 |
|---|---|---|
print "hello" (语句) | print("hello") (函数) | |
| 整数除法 | 3/2 = 1 | 3/2 = 1.5 |
| 字符串 | 默认 ASCII | 默认 Unicode |
| range | 返回列表 | 返回迭代器 |
| input | raw_input() | input() |
结论:现在学 Python 只需要学 Python 3。
1.3 安装 Python
Windows
- 访问 python.org 下载最新版
- 安装时务必勾选 “Add Python to PATH”
- 打开命令行验证:
python --version
# Python 3.13.x
macOS
macOS 自带的 Python 版本通常较旧,推荐用 Homebrew 安装:
brew install python
python3 --version
Linux
大多数发行版自带 Python 3:
# Ubuntu / Debian
sudo apt update && sudo apt install python3 python3-pip
# CentOS / RHEL
sudo dnf install python3
推荐:使用 uv 管理 Python 版本
uv 是新一代 Python 包管理工具,可以一键安装和管理多个 Python 版本:
# 安装 uv
curl -LsSf https://astral.sh/uv/install.sh | sh # Linux/macOS
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Windows
# 安装指定版本 Python
uv python install 3.13
# 查看已安装版本
uv python list
1.4 交互式解释器(REPL)与 IDLE
REPL(Read-Eval-Print Loop)
在终端输入 python 即可进入交互模式:
>>> 2 + 3
5
>>> "hello" * 3
'hellohellohello'
>>> type(42)
<class 'int'>
Python 3.13 带来了全新的交互式解释器,支持多行编辑、语法高亮和更好的错误提示。
退出 REPL:输入 exit() 或按 Ctrl+D(Linux/macOS)/ Ctrl+Z 后回车(Windows)。
IDLE
Python 自带的简易 IDE,适合初学者快速实验。安装 Python 后即可在开始菜单找到。
更好的选择
实际开发推荐使用:
- VS Code + Python 扩展
- PyCharm(社区版免费)
- Cursor(AI 辅助编程)
1.5 第一个 Python 程序:Hello, World!
创建文件 hello.py:
print("Hello, World!")
运行:
python hello.py
# 输出: Hello, World!
一个稍微复杂的例子——猜数字游戏,展示 Python 的简洁:
import random
number = random.randint(1, 100)
print("我想了一个 1-100 的数字,猜猜看!")
while True:
guess = int(input("你的猜测: "))
if guess < number:
print("太小了!")
elif guess > number:
print("太大了!")
else:
print("恭喜,猜对了!")
break
1.6 代码风格与 PEP 8 规范
PEP 8 是 Python 官方的代码风格指南,以下是最重要的规则:
缩进
使用 4 个空格,不使用 Tab:
# 正确
def greet(name):
if name:
print(f"Hello, {name}!")
# 错误 — 混合使用 Tab 和空格会导致错误
命名规范
# 变量和函数:snake_case
user_name = "Alice"
def get_user_info():
pass
# 类名:PascalCase
class UserProfile:
pass
# 常量:ALL_CAPS
MAX_RETRY_COUNT = 3
PI = 3.14159
# 私有属性/方法:前缀下划线
_internal_cache = {}
def _helper():
pass
行长度
每行不超过 79 个字符(现代项目常放宽到 88 或 120):
# 长表达式换行
result = (first_variable
+ second_variable
- third_variable)
# 长函数参数
def long_function(
argument_one,
argument_two,
argument_three,
):
pass
空行
- 顶层函数和类之间空 2 行
- 类中方法之间空 1 行
导入顺序
# 1. 标准库
import os
import sys
# 2. 第三方库
import requests
# 3. 本地模块
from myproject import utils
自动格式化工具
不必死记规则,使用工具自动格式化:
# ruff — 目前最快的 Python linter + formatter
pip install ruff
ruff format your_file.py
ruff check your_file.py
# black — 经典的格式化工具
pip install black
black your_file.py
本章小结:Python 是一门设计哲学明确、语法简洁优雅的语言。搭好环境、写出第一个程序、了解代码规范,你已经迈出了第一步。接下来我们将深入了解 Python 的基本数据类型。