编码 · 编程语言
Python 入门教程(零基础)
简短回答
Python 是一门通用的解释型语言,以可读性强的语法著称,用缩进代替花括号。安装 Python 3,把 print("Hello, world") 保存为 hello.py,然后运行 python3 hello.py。核心概念包括:动态类型、用 def 定义的函数、内置的列表、字典和集合、用 try/except 处理的异常,以及庞大的标准库。
Python 是什么,用来做什么
Python 是一门高级、动态类型的语言,由 Guido van Rossum 于 1991 年首次发布。代码由解释器运行(官方参考实现是 CPython),因此没有单独的编译步骤。它被广泛用于数据分析和机器学习(NumPy、pandas、PyTorch)、Web 后端(Django、Flask、FastAPI)、自动化脚本、科学计算和教学。Python 2 已在 2020 年停止维护,所以请直接学习 Python 3。
安装 Python 并运行 Hello, world
在 python.org 下载安装包(Windows、macOS),Linux 上可使用包管理器安装。用 python3 --version 检查是否安装成功(Windows 上命令通常是 py 或 python)。把下面的代码保存为 hello.py:
print("Hello, world")python3 hello.py
# Hello, world不带文件直接运行 python3 会进入交互式命令行(REPL),适合一行一行地试验代码。
变量与基本类型
给变量赋值就创建了变量,无需声明类型;类型跟着值走,用 type(x) 可以查看。
| 类型 | 示例 | 说明 |
|---|---|---|
int | 42, -7, 10**20 | 任意大小的整数 |
float | 3.14, 1e-3 | 64 位浮点数 |
bool | True, False | 首字母大写 |
str | "hi", 'hi' | 不可变的 Unicode 文本 |
None | None | 表示“没有值” |
name = "Ada"
age = 36
height = 1.65
print(f"{name} is {age} years old") # Ada is 36 years old
print(7 / 2, 7 // 2, 7 % 2) # 3.5 3 1
print(int("12") + 1) # 13流程控制:if、for 和 while
代码块以冒号开头,由缩进界定(惯例是 4 个空格)。for 循环可以遍历任意序列;range(n) 生成 0 到 n−1 的数字。
score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"
print(grade) # B
for i in range(3):
print(i) # 0, then 1, then 2
n = 10
while n > 1:
n = n // 2
print(n) # 1函数
用 def 定义函数。参数可以有默认值,调用时也可以按名称传参。没有 return 的函数返回 None。
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Lin")) # Hello, Lin!
print(greet("Lin", greeting="Hi")) # Hi, Lin!
square = lambda x: x * x
print(square(5)) # 25类型提示(如 def area(w: float, h: float) -> float:)可以说明意图,并让 mypy 等工具检查代码,但解释器本身并不强制执行。
列表、元组、字典和集合
| 类型 | 字面量 | 有序 | 可变 | 典型用途 |
|---|---|---|---|---|
list | [1, 2, 3] | 是 | 是 | 会被修改的序列 |
tuple | (1, 2) | 是 | 否 | 固定的一组值 |
dict | {"a": 1} | 按插入顺序 | 是 | 按键查找值 |
set | {1, 2} | 否 | 是 | 去重、判断成员是否存在 |
nums = [3, 1, 2]
nums.append(5)
nums.sort()
print(nums, nums[0], nums[-1], nums[1:3]) # [1, 2, 3, 5] 1 5 [2, 3]
ages = {"ann": 31, "bob": 25}
ages["cy"] = 40
for person, age in ages.items():
print(person, age)
print(ages.get("zed", 0)) # 0
squares = [x * x for x in range(5) if x % 2 == 0]
print(squares) # [0, 4, 16]最后一行是列表推导式,是 Python 的标志性特性:用一个表达式就能通过循环和可选的过滤条件生成列表。字典推导式和集合推导式的写法与之类似。
标志性特性:解包、with 与生成器
a, b = 1, 2
a, b = b, a # swap without a temporary
first, *rest = [1, 2, 3, 4]
print(first, rest) # 1 [2, 3, 4]
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("line one\n") # file is closed automatically
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1]with 语句会替你执行准备和清理代码(这里即使出错也会关闭文件)。使用 yield 的函数是生成器:它惰性地逐个产生值,处理大数据时可以节省内存。
用 try 和 except 处理错误
错误以异常的形式抛出。请捕获你预期的具体异常类型,需要无论如何都执行的代码放在 finally 中。
def parse_age(text):
try:
age = int(text)
except ValueError:
print(f"not a number: {text!r}")
return None
if age < 0:
raise ValueError("age cannot be negative")
return age
print(parse_age("41")) # 41
print(parse_age("abc")) # not a number: 'abc', then None一个完整的小程序:词频统计
这个脚本读取命令行指定的文本文件,并输出出现次数最多的五个单词。它只用到标准库。
import sys
from collections import Counter
def top_words(path, n=5):
with open(path, encoding="utf-8") as f:
words = f.read().lower().split()
cleaned = [w.strip(".,;:!?\"'()") for w in words]
return Counter(w for w in cleaned if w).most_common(n)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: python3 count.py FILE")
try:
for word, count in top_words(sys.argv[1]):
print(f"{count:5} {word}")
except FileNotFoundError:
sys.exit(f"file not found: {sys.argv[1]}")用 python3 count.py notes.txt 运行。if __name__ == "__main__": 这一判断让文件既能作为模块被导入而不执行脚本部分。
新手常见错误
- 混用制表符和空格,或缩进不一致,会引发
IndentationError。请把编辑器设置为插入 4 个空格。 =是赋值,==是比较。is只用于判断None(if x is None)。input()总是返回字符串;做数学运算前要用int()或float()转换。- 用
b = a并不会复制列表,两个名字指向的是同一个列表。请用b = a.copy()或b = list(a)。 - 请在虚拟环境(
python3 -m venv .venv)中安装第三方包,不要装进系统自带的 Python。
接下来学什么
先完整过一遍官方的 Python Tutorial,再浏览 Library Reference,了解 pathlib、json、datetime、itertools 等模块。学会用 pip 和虚拟环境管理第三方包,并用 unittest 或 pytest 写测试。之后选择一个方向:Web(Django 或 FastAPI)、数据(pandas)或自动化。
常见问题
Python 适合零基础入门吗?
适合。它的语法简短,接近自然英语,报错信息清晰,还能在 REPL 中逐行试验代码。同时它在工业界应用广泛,入门所学的技能长期有用。
Python 是编译型还是解释型语言?
CPython 先把源码编译成字节码,再解释执行字节码,这一切在运行脚本时自动完成,你不需要单独执行编译步骤。
列表和元组有什么区别?
列表是可变的:可以添加、删除和修改元素。元组是不可变的,用来表示固定的一组值,并且可以作为字典的键。
为什么我的 Python 代码很慢?
纯 Python 循环比编译型语言慢。请尽量使用内置函数、推导式,以及 NumPy 这类内部循环用 C 实现的库。
命令行中该用 python 还是 python3?
在 macOS 和大多数 Linux 系统上请使用 python3,因为 python 可能不存在或指向别的东西。Windows 上通常使用 py 启动器。