Program จะทำอะไรสักอย่างก็ต่อเมื่อคุณรันมันเท่านั้น
Source code runs through the interpreter to produce output
1.2
Comments & code style
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 错误.
ไทย
Comment เริ่มด้วย # Python จะ ignore ทุกอย่างหลัง # บนบรรทัดนั้น Comment อธิบายโค้ดของคุณให้กับผู้อื่น—they do not change what the code does.
# This line is a note for humans
print("Hi") # you can also comment at the end of a line
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
List comprehensions
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
Tuples & sets
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 เพื่อทดสอบ presence ของ key. โน้ตผ่าน keys, หรือผ่าน .items() เพื่อรับทั้ง key และ value
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
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
การทดสอบและความทนทาน (Testing & robustness)
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("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
การเพิ่มต่อ (Appending)
Mode "a" เพิ่มต่อ — เพิ่มที่ท้ายโดยไม่ลบ
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
Mode
ความหมาย
"r"
read (ค่าเริ่มต้น)
"w"
write (ลบก่อน)
"a"
append (เพิ่มที่ท้าย)
ข้อผิดพลาดที่พบบ่อย
ปิดไฟล์เสมอ หรือใช้ with open(...) as f: ที่ปิดให้
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.
ไทย
Recursion คือฟังก์ชันเรียกตัวเอง ต้องการ base case (อินพุตง่ายที่คืนค่าทันที) และ recursive case (เรียกตัวเองกับอินพุตเล็กลง)
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) อธิบายข้อมูลพร้อม operation แยกจากวิธีการสร้าง ใช้ผ่าน operation ไม่ใช่การจัดเก็บภายใน
# 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
Stack
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
ไทย
Stack เป็น Last-in, First-out (LIFO) Push ด้านบน Pop ด้านบน
Stack ลบจากบน (LIFO); Queue ลบจากหน้า (FIFO)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
Queue
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
Hash tables
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.
ไทย
Hash table映射 key กับ slot ด้วย hash function Two keys落地同一slot = Collision Python's dict เป็น hash table ดังนั้นค้นหาเร็ว
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
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]
def insertion_sort(a):
a = a[:] # work on a copy
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # shift bigger values right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key # drop key into the gap
return a
print(insertion_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
ในโค้ดจริง ให้ใช้ sorted() ในPython builtin:
print(sorted([5, 2, 4, 1])) # [1, 2, 4, 5]
13.3
ประสิทธิภาพของอัลกอริทึม
English
Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.
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
แนวคิดการเขียนโปรแกรม
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.
ไทย
Paradigmคือสไตล์การเขียนโปรแกรม โค้ด proceduralคือลำดับขั้นตอนและ functions. โค้ด object-orientedรวม data และメソッドเข้าด้วยกันเป็น objects. โค้ด declarativeบอก what คุณต้องการ ไม่ใช่ how (list comprehension หรือ SQL)
def total(nums): # procedural
t = 0
for n in nums:
t += n
return t
print(total([1, 2, 3])) # 6
print(sum([1, 2, 3])) # 6 (declarative: same result)
ข้อผิดพลาดที่พบบ่อย
Everyメ道ต้อง self เป็น first parameter ของมัน
__init__ ตั้งค่า new object และรันอัตโนมัติเมื่อคุณสร้างมัน
Two objects ของ same class มี separate attributes; เปลี่ยน one ไม่ทำให้ 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.
Run-length encodingเป็นวิธี lossless ง่าย: เก็บ run (repeat) เป็น count plus ค่า
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.
ไทย
โปรเจกต์ย่อยรวมแนวคิดเดิมๆ เข้าด้วยกัน: ข้อมูลในลิสต์ ฟังก์ชันที่มีคำสั่งเลือกภายในลูป และการพิมพ์ผลลัพธ์ นี่คือรูปแบบของ AP Create Performance Task
Pick one and the site follows you — notes, papers, videos and practice all open on it. · เลือกหนึ่งตัว และเว็บจะติดตามคุณ — หมายเหตุ, ใบงาน, วิดีโอ และการฝึกฝนจะเปิดอยู่ที่นั้น
Type to search notes, lessons, code, vocabulary and past-paper questions across every subject. · พิมพ์เพื่อค้นหาบันทึก, บทเรียน, โค้ด, คำศัพท์ และคำถามข้อสอบเก่าในทุกวิชา