print("Hello, world!")
print("I am learning Python")
每个 print() 另起一行。
引号可以是单引号 "double" 或双引号 'single' ——两者都构成字符串。
程序只有在你运行它时才会工作。
源代码通过解释器运行以产生输出
1.2
注释与代码风格
English
A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.
Good style makes code easy to read:
Use clear names that say what a value means.
Put one statement on each line.
Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.
input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:
int("abc") fails, so only convert text that looks like a number.
Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value, end=" ")
print() # 1 2 3 4
6.4
列表推导式
English
A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].
Add if to keep only some items.
中文
列表推导式(list comprehension)用一行就能构建一个新列表:[expression for item in sequence]。
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
加上 if 只保留部分元素。
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
6.5
元组与集合
English
A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.
A function that needs to hand back two results returns a tuple:
A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.
Common mistakes
b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
The last item is a[-1]; a[len(a)] is out of range.
append adds ONE item; use extend or + to join another list.
Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
A tuple with one item needs a comma: (5,), not (5).
A set has no order and no duplicates, so you cannot index it with s[0].
student = {"name": "Mei"}
student["score"] = 88 # add a new key
student["score"] = 90 # update the value
print(student) # {'name': 'Mei', 'score': 90}
检查与遍历
用 in 检查某个键是否存在。遍历所有键,或遍历 .items() 同时得到键和值。
student = {"name": "Mei", "score": 90}
print("score" in student) # True
for key, value in student.items():
print(key, "=", value)
# name = Mei
# score = 90
Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.
Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
# A runtime error, caught so this block still finishes:
try:
print(10 / 0)
except ZeroDivisionError:
print("cannot divide by zero")
# cannot divide by zero
Python 会打印一段回溯(traceback),显示在哪里出错。从下往上读它。
Common Python errors: Syntax, Name, Type, Index
9.2
try / except / raise
English
Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.
Catch a specific type (ValueError, ZeroDivisionError, …).
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
try:
set_age(-1)
except ValueError as err:
print("error:", err)
# error: age cannot be negative
9.3
测试与健壮性
English
A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.
Robust 健壮 code does not crash on strange input; it handles it gracefully.
Common mistakes
Do not use a bare except: — catch the specific error, e.g. except ValueError:.
A syntax error stops the whole program before it runs, so fix those first.
Test the edge cases (empty input, zero, the largest value), not just the easy one.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print("saved") # saved
读取
模式 "r"(默认)用来读。.read() 把整个文件作为一个字符串返回。
with open("notes.txt", "w") as f:
f.write("hello\nworld\n")
with open("notes.txt") as f:
print(f.read().strip()) # hello / world
逐行读取
遍历文件,一次得到一行。.strip() 会去除(remove)末尾的换行符(newline)。
with open("data.txt", "w") as f:
f.write("Mei,88\nSam,71\n")
with open("data.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(name, "scored", score)
# Mei scored 88
# Sam scored 71
追加
模式 "a" 追加(append)——它在末尾添加,而不抹掉原有内容。
with open("log.txt", "w") as f:
f.write("line 1\n")
with open("log.txt", "a") as f:
f.write("line 2\n")
with open("log.txt") as f:
print(f.read().strip()) # line 1 / line 2
An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.
Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
# Algorithm: find the largest number in a list
def largest(nums):
best = nums[0]
for n in nums:
if n > best:
best = n
return best
print(largest([3, 9, 2, 7])) # 9
Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).
Each paused call sits on the call stack 调用栈 until the call above it returns.
Common mistakes
Recursion needs a base case, or it calls itself forever and crashes the call stack.
Pseudocode is for planning — it need not run, but every step must be unambiguous.
Break a big problem into small named steps before you write any code.
An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.
中文
抽象数据类型(abstract data type,ADT)描述一些数据以及对它的操作,与它如何实现分开。你通过它的操作来使用它,而不是通过它内部的存储方式。
# A stack ADT, built on a list
s = []
s.append(1) # add
s.append(2)
print(s.pop()) # 2 (remove the most recent)
12.2
栈
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
中文
栈(stack)是后进先出(LIFO)。你把元素压入(push)栈顶,也从栈顶弹出(pop)。
栈从顶部移除(后进先出);队列从前端移除(先进先出)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
队列
English
A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.
n3 = {"data": 3, "next": None}
n2 = {"data": 2, "next": n3}
n1 = {"data": 1, "next": n2}
node = n1
while node is not None: # traverse to the end
print(node["data"])
node = node["next"]
# 1 2 3
12.5
哈希表
English
A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1 # not found
print(linear_search([4, 8, 2, 9], 2)) # 2
二分查找(binary search)快得多,但需要一个已排序的列表。它每一步把范围折半。
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
二分查找每一步把范围减半——已排序列表上是 O(log n)
13.2
排序(冒泡与插入)
English
To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.
Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:
def bubble_sort(a):
a = a[:] # work on a copy
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.
name is an attribute 属性 (data on the object); speak is a method 方法 (an action).
class Cat:
def speak(self):
return "meow"
class Cow:
def speak(self):
return "moo"
for animal in [Cat(), Cow()]:
print(animal.speak()) # meow, then moo
14.3
Programming paradigms · 编程范式
English
A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).
Common mistakes
Every method needs self as its first parameter.
__init__ sets up a new object and runs automatically when you create one.
Two objects of the same class have separate attributes; changing one does not change the other.
A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.
8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:
Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.
Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.
Common mistakes
n bits store 2**n different values, from 0 up to 2**n - 1.
Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
def rle(text):
out = ""
i = 0
while i < len(text):
run = 1
while i + run < len(text) and text[i + run] == text[i]:
run += 1
out += str(run) + text[i]
i += run
return out
print(rle("AAAABBBCCD")) # 4A3B2C1D
Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.
Break a problem down, build a small part, test it, then add more.
Programmers work in teams and reuse each other's code.
The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.
Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.
Not everything can run in parallel: some steps must wait for an earlier result.
Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.
Common mistakes
The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
More processor cores help only if the work can be split into parts that run at the same time.
A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.
Project: average mark
Project: count passes
Project: filter to a new list
The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.
Common mistakes
Build in small steps and test each part before moving on — do not write it all at once.
Read the whole task first, then plan the input → process → output before you code.
中文
一个小项目(mini-project)把前面学过的想法组合起来:列表里的数据、一个在循环里带选择的函数,以及打印出的输出。这也是 AP 创作型表现任务的形态。