Functions and Modular Design函数与模块化设计
Functions are the core tool for writing reusable, readable, and maintainable code. Instead of copying the same logic in five places, you define it once as a named function and call it wherever you need it. This guide builds every concept from scratch: what a function is and why you need one; how to define and call functions; how parameters and arguments let you pass data in; how return values send results out; how variable scope controls which names are visible where; how modular design organises a whole program as a network of cooperating functions; and how built-in functions and libraries save you from reinventing the wheel. All examples use pseudocode and Python side by side.函数(function,函数)是编写可复用、可读性强、易于维护代码的核心工具。与其在五个地方复制同一段逻辑,不如将其定义为一个具名函数(named function,具名函数),在需要时调用(call,调用)。本指南从零开始建立每个概念:函数是什么以及为何需要它;如何定义和调用函数;形参(parameter,形参)和实参(argument,实参)如何让你传入数据;返回值(return value,返回值)如何将结果传出;作用域(scope,作用域)如何控制哪些名称在哪里可见;模块化设计(modular design,模块化设计)如何将整个程序组织为协作函数的网络;以及内置函数(built-in function,内置函数)和库(library,库)如何避免重复造轮子。所有示例均同时使用伪代码和 Python 演示。
How to use this guide如何使用本指南
Functions and modular design appear in every curriculum we map to. Ontario ICS3U strand A3 explicitly requires students to write subprograms using parameter passing and variable scope. Alberta CSE2110 formalises procedural programming with functions, procedures, scope, and parameter passing. AP CSP Big Idea 3 (topics 3.12–3.14) tests calling and defining procedures and using libraries. BC Computer Programming 11 names "structures" and "pre-built libraries." All four agree on the core concepts covered here. Where curricula diverge is on depth: ICS4U C1.3 adds functional decomposition as a design process (Grade-12 Honors); BC CP12 adds "management of complexity." The table below locates you.函数与模块化设计出现在我们所对应的每个大纲中。安大略 ICS3U A 单元第 3 条(A3)明确要求学生使用参数传递和变量作用域编写子程序。阿尔伯塔 CSE2110 将函数、过程、作用域和参数传递正式化为过程化编程。AP CSP 大概念 3(主题 3.12–3.14)考查调用和定义过程以及使用库。BC Computer Programming 11 点名"结构"和"预建库"。四套大纲在此涵盖的核心概念上高度一致。大纲的分歧在于深度:ICS4U C1.3 将函数分解作为设计过程(12 年级荣誉级别);BC CP12 增加"复杂性管理"。下表帮助你定位。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP | §1 through §7. CSTA 3A-AP-17 (decompose using procedures/modules) and 3A-AP-18 (create artifacts using procedures) both apply. AP CSP topics 3.12–3.14 (calling procedures, developing procedures, libraries) are directly tested.§1 至 §7。CSTA 3A-AP-17(使用过程/模块分解)和 3A-AP-18(使用过程创建制品)均适用。AP CSP 主题 3.12–3.14(调用过程、开发过程、库)直接考查。 | §5 scope going-deeper (global state hazards) is enrichment for AP CSP floor students; the exam tests local/global at a conceptual level.§5 作用域深入(全局状态风险)对 AP CSP 基础学生为拓展内容;考试在概念层面考查局部/全局。 | CSTA K-12 and AP CSP — CSTA 3A-AP-17, 3A-AP-18; AP CSP Big Idea 3 (AAP) topics 3.12, 3.13, 3.14; LO AAP-3.B— CSTA 3A-AP-17、3A-AP-18;AP CSP 大概念 3(AAP)主题 3.12、3.13、3.14;学习目标 AAP-3.B |
| 🇨🇦 ON Grade 11 — ICS3U安大略 11 年级 — ICS3U | §1 through §7. ICS3U A3 (write subprograms using parameter passing and variable scope) and B2.3 (apply modularity for reusable code) are the primary targets. §2–§5 cover the exact skills assessed in A3.2.§1 至 §7。ICS3U A3(使用参数传递和变量作用域编写子程序)和 B2.3(应用模块化设计可复用代码)是主要目标。§2–§5 涵盖 A3.2 考查的确切技能。 | Functional decomposition as formal design process (ICS4U C1.3) is Grade 12 — skip the Honors going-deeper boxes for ICS3U floor.函数分解作为正式设计过程(ICS4U C1.3)属 12 年级——ICS3U 基础学生跳过荣誉深入框。 | ON/BC Computer Studies 11-12 — ICS3U A3, A3.1, A3.2, B2.3; ICS4U C1.3— ICS3U A3、A3.1、A3.2、B2.3;ICS4U C1.3 |
| 🇨🇦 BC — CP11 / CP12BC — CP11 / CP12 | §1 through §7. CP11 names "structures" and "pre-built libraries and their documentation" as core content. Every section here maps to those topics.§1 至 §7。CP11 将"结构"和"预建库及其文档"列为核心内容。本指南每一节均对应这些主题。 | "Advanced programming structures" and "Management of complexity" (CP12) are Honors enrichment for BC CP11 floor students."高级编程结构"和"复杂性管理"(CP12)对 BC CP11 基础学生属荣誉拓展。 | ON/BC Computer Studies 11-12 — BC CP11 "structures", "pre-built libraries"; CP12 "Advanced programming structures", "Management of complexity"— BC CP11"结构"、"预建库";CP12"高级编程结构"、"复杂性管理" |
| 🇨🇦 AB — CSE2110阿尔伯塔 — CSE2110 | §1 through §7. CSE2110 Procedural Programming 1 is the best match: subprograms, functions vs procedures, scope, one- and two-way parameter passing. This guide covers exactly CSE2110 outcomes 3.2, 3.3, 3.4.§1 至 §7。CSE2110 过程化编程 1 是最佳匹配:子程序、函数与过程、作用域、单向和双向参数传递。本指南正好涵盖 CSE2110 结果 3.2、3.3、3.4。 | Object-oriented modularity (CSE3120) is a later Advanced-level topic — not covered here.面向对象模块化(CSE3120)是后续高级模块——本指南不涵盖。 | Alberta CTS Computing Science — CSE2110 outcomes 3.2, 3.3, 3.4— CSE2110 结果 3.2、3.3、3.4 |
Once you have located your row, use the two cards below for the pace at which to work through the sections.找到所在行后,用下面两张卡片决定推进速度。
Memorise four things: what a function is and why you need one; how to define and call a function in pseudocode; what a parameter is and what a return value is; and the difference between local and global scope. Read every cram-cheat box. Skip the going-deeper boxes.背熟四件事:函数是什么以及为何需要它;如何用伪代码定义和调用函数;形参是什么以及返回值是什么;局部作用域与全局作用域的区别。读每个速记框,跳过深入框。
Practise the full define-call-trace cycle for every worked example: write the function definition, call it with concrete arguments, trace the execution step by step including the return. AP CSP topics 3.12–3.14 expect you to read procedure definitions and predict their output. Ontario ICS3U A3.2 requires you to write functions with parameter passing and correct scope. Both skills are fully covered here.对每个例题练习完整的定义-调用-追踪循环:编写函数定义,用具体实参调用,逐步追踪执行过程(包括返回)。AP CSP 主题 3.12–3.14 要求你读懂过程定义并预测其输出。安大略 ICS3U A3.2 要求你编写具有参数传递和正确作用域的函数。这两项技能本指南均完整涵盖。
Why Functions? Reuse and Abstraction为什么要用函数?复用与抽象
- Reuse复用 — define the logic once; call it anywhere. No copy-paste. If the logic changes, you change one place and all callers get the fix. CSTA 3A-AP-18: "Create artifacts by using procedures within a program."— 定义逻辑一次,在任何地方调用。无需复制粘贴。如果逻辑需要更改,只需修改一处,所有调用方都获得修复。CSTA 3A-AP-18:"通过在程序中使用过程来创建制品。"
- Abstraction抽象 — the caller only needs to know what the function does (its name, inputs, output), not how it does it. This hides complexity and lets you think at a higher level. AP CSP LO AAP-3.B: "Use abstraction to manage complexity in a program."— 调用方只需知道函数做什么(名称、输入、输出),而不需要知道如何做。这隐藏了复杂性,让你在更高层次上思考。AP CSP 学习目标 AAP-3.B:"使用抽象管理程序中的复杂性。"
- Decomposition分解 — split a big program into small, independently testable functions. Each function solves one clearly-named sub-problem. CSTA 3A-AP-17: "Decompose problems into smaller components … using constructs such as procedures, modules."— 将大型程序拆分为小型、可独立测试的函数。每个函数解决一个命名清晰的子问题。CSTA 3A-AP-17:"通过使用过程、模块等构造将问题分解为更小的组件。"
math.sqrt(9) you do not need to know the algorithm inside — you just trust the interface. Building your own functions gives the same benefit to whoever calls yours.最易踩坑的一点:函数是一种抽象,不仅仅是快捷方式。当你调用 math.sqrt(9) 时,你不需要知道内部算法——只需信任接口。构建自己的函数,就能给调用者带来同样的好处。
Problem: a program needs to compute the area of a rectangle in three different places. Show the repeated-code version and the function version.问题:一个程序在三处不同地方需要计算矩形面积。展示重复代码版和函数版。
Repeated-code version (bad).重复代码版(不好)。
-- Place 1
SET area1 TO 5 * 3
-- Place 2
SET area2 TO 8 * 4
-- Place 3
SET area3 TO 12 * 7
Three places repeat the same logic (width × height). If the formula needs to change, you must edit three places.三处代码重复相同逻辑(宽 × 高)。如需改为"宽 × 高 × 比例因子",必须修改三处。
Function version (good).函数版(好)。
FUNCTION rectangle_area(width, height):
RETURN width * height
SET area1 TO rectangle_area(5, 3)
SET area2 TO rectangle_area(8, 4)
SET area3 TO rectangle_area(12, 7)
Python rendering.Python 实现。
def rectangle_area(width, height):
return width * height
area1 = rectangle_area(5, 3) # 15
area2 = rectangle_area(8, 4) # 32
area3 = rectangle_area(12, 7) # 84
The logic lives in one place. The callers are readable (“rectangle area of 5 by 3”) without needing to see the multiplication. Ontario ICS3U B2.3: "apply the principle of modularity to design reusable code."逻辑只存在于一处。调用方具有可读性("5 乘 3 的矩形面积"),无需看到乘法运算。安大略 ICS3U B2.3:"应用模块化原则设计可复用代码。"
Going deeper — procedural abstraction and the “black box” model深入 — 过程抽象与"黑盒"模型
Computer scientists describe functions using a black box model: inputs go in, outputs come out, and the internal implementation is hidden. This separation of interface (what the function promises) from implementation (how it does it) is what allows large teams to build large systems: one developer writes sort_list(data); every other developer can use it without understanding the sorting algorithm. BC Computer Programming 12 names this "Management of complexity." Ontario ICS4U C1.3 formalises it as "functional decomposition in subprogram design." Alberta CSE2110 outcome 1.1.5 notes "hiding or protecting the program data" as an advantage of modular programming. The principle scales from a 20-line student project to a million-line operating system.计算机科学家使用黑盒模型描述函数:输入进去,输出出来,内部实现被隐藏。接口(函数承诺做什么)与实现(如何做到)的分离,使大型团队能够构建大型系统:一个开发者编写 sort_list(data);其他所有开发者都可以使用它而无需理解排序算法。BC Computer Programming 12 将此称为"复杂性管理"。安大略 ICS4U C1.3 将其正式化为"子程序设计中的函数分解"。阿尔伯塔 CSE2110 结果 1.1.5 指出"隐藏或保护程序数据"是模块化编程的优势。这个原则适用范围从 20 行的学生项目到百万行的操作系统。
Defining and Calling Functions定义与调用函数
- Definition (FUNCTION keyword)定义(FUNCTION 关键字) — creates the named block of code. In pseudocode:
FUNCTION name(params): ... END FUNCTION. In Python:def name(params): .... Defining a function does NOT run it.— 创建具名代码块。伪代码:FUNCTION name(params): ... END FUNCTION。Python:def name(params): ...。定义函数不会运行它。 - Call (invoking the function)调用(调用函数) — runs the code inside the function. In pseudocode:
CALL name(args)or justname(args). In Python:name(args). The program jumps into the function body, executes it, then returns to where the call was.— 运行函数内部的代码。伪代码:CALL name(args)或直接name(args)。Python:name(args)。程序跳入函数体,执行后返回调用处。
Problem: write a function that prints a greeting for a given name, then call it twice with different names.问题:编写一个函数,为给定姓名打印问候语,然后用不同姓名调用两次。
Pseudocode definition and calls.伪代码定义与调用。
FUNCTION greet(name):
OUTPUT "Hello, " + name + "!"
END FUNCTION
CALL greet("Alice")
CALL greet("Bob")
伪代码说明:FUNCTION 定义函数,OUTPUT 输出,CALL 调用,name 为形参(parameter,形参)。Pseudocode: FUNCTION defines, OUTPUT prints, CALL invokes, name is the parameter.
Python rendering.Python 实现。
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
The def line defines the function; neither print runs until a call occurs. Each call creates a fresh execution of the function body, with the given argument bound to the parameter name.def 行定义函数;在调用发生之前,两次打印都不会运行。每次调用都会重新执行函数体,将给定的实参绑定到形参 name。
def to begin a function definition: def function_name(params):. The function keyword in pseudocode is FUNCTION; in AP CSP pseudocode it is PROCEDURE; but in Python it is always def.Python 使用 def 开始函数定义:def function_name(params):。伪代码中的函数关键字是 FUNCTION;AP CSP 伪代码中是 PROCEDURE;但在 Python 中始终是 def。def (short for define), not function or define. PROCEDURE is the AP CSP pseudocode keyword.在 Python 中,关键字是 def(define 的缩写),而不是 function 或 define。PROCEDURE 是 AP CSP 伪代码关键字。Going deeper — AP CSP pseudocode: PROCEDURE vs Python def深入 — AP CSP 伪代码:PROCEDURE 与 Python def 对比
AP CSP uses its own reference-sheet pseudocode for procedures: PROCEDURE name(param1, param2) { ... }. The call syntax is name(arg1, arg2). Boolean values are TRUE/FALSE; display uses DISPLAY(value); assignment uses the arrow x ← value. This guide uses the generic pseudocode keywords (FUNCTION / RETURN / OUTPUT) that map to any language. For the AP CSP exam, apply the College Board reference sheet notation directly. The underlying concepts (define once, call many times, parameter binding, return value) are identical in both notations.AP CSP 使用其自己的参考手册伪代码定义过程:PROCEDURE name(param1, param2) { ... }。调用语法是 name(arg1, arg2)。布尔值为 TRUE/FALSE;显示使用 DISPLAY(value);赋值使用箭头 x ← value。本指南使用通用伪代码关键字(FUNCTION / RETURN / OUTPUT),可映射到任何语言。对于 AP CSP 考试,直接应用 College Board 参考手册表示法。底层概念(定义一次、多次调用、参数绑定、返回值)在两种表示法中完全相同。
Parameters and Arguments形参与实参
- Parameter形参(parameter) — the variable name in the function definition. It is a placeholder: it has a name but no value until the function is called. In
FUNCTION area(width, height),widthandheightare parameters.— 函数定义中的变量名。它是占位符:有名称但在函数被调用之前没有值。在FUNCTION area(width, height)中,width和height是形参。 - Argument实参(argument) — the actual value passed at the call site. In
area(5, 3),5and3are arguments. At call time,widthgets5andheightgets3.— 在调用处传递的实际值。在area(5, 3)中,5和3是实参。调用时,width得到5,height得到3。 - One-way parameter passing单向参数传递 — the function receives the value; changing the parameter inside the function does not affect the caller's variable. AB CSE2110 outcome 3.3.3 covers "one- and two-way parameter passing."— 函数接收值;在函数内部更改形参不影响调用方的变量。AB CSE2110 结果 3.3.3 涵盖"单向和双向参数传递"。
Problem: write a function power(base, exponent) that returns base raised to the exponent, then call it with three different argument pairs.问题:编写函数 power(base, exponent),返回底数的指数次幂,然后用三对不同的实参调用它。
Pseudocode.伪代码。
FUNCTION power(base, exponent):
SET result TO 1
FOR i FROM 1 TO exponent:
SET result TO result * base
RETURN result
END FUNCTION
OUTPUT power(2, 3) -- 8
OUTPUT power(3, 4) -- 81
OUTPUT power(5, 2) -- 25
说明:base 和 exponent 是形参(parameter,形参);2, 3 / 3, 4 / 5, 2 是实参(argument,实参)。RETURN 将结果传回调用处。Note: base and exponent are parameters; 2, 3 / 3, 4 / 5, 2 are arguments. RETURN sends the result back to the caller.
Python rendering.Python 实现。
def power(base, exponent):
result = 1
for i in range(exponent):
result = result * base
return result
print(power(2, 3)) # 8
print(power(3, 4)) # 81
print(power(5, 2)) # 25
Each call creates fresh copies of base and exponent with the given argument values. Changing result inside the function does not affect any variable outside — that is one-way parameter passing in action.每次调用都会创建 base 和 exponent 的新副本,并绑定给定的实参值。在函数内更改 result 不会影响函数外的任何变量——这就是单向参数传递的实际效果。
FUNCTION square(n): RETURN n * n, what is n?在 FUNCTION square(n): RETURN n * n 中,n 是什么?n appears in the function definition, so it is a parameter. It is a placeholder that receives the actual value when the function is called. E.g., square(7) binds n = 7; square(9) binds n = 9.n 出现在函数定义中,所以它是形参。它是一个占位符,在函数被调用时接收实际值。例如,square(7) 绑定 n = 7;square(9) 绑定 n = 9。n is in the definition — it is a parameter. The return value is n * n.形参在定义中;实参在调用处。n 在定义中——它是形参。返回值是 n * n。FUNCTION add(a, b): RETURN a + b. What is the result of add(4, 7)?函数定义为 FUNCTION add(a, b): RETURN a + b。add(4, 7) 的结果是什么?add(4, 7), argument 4 binds to parameter a and argument 7 binds to parameter b. The function returns 4 + 7 = 11.调用 add(4, 7) 时,实参 4 绑定到形参 a,实参 7 绑定到形参 b。函数返回 4 + 7 = 11。a = 4, b = 7. The return value is a + b = 4 + 7 = 11.实参按顺序绑定:a = 4,b = 7。返回值是 a + b = 4 + 7 = 11。Return Values返回值
- Void / procedure (no return)无返回值函数 / 过程 — does something (prints, modifies a structure) but produces no output value. Example:
greet("Alice")just prints; nothing comes back to assign. AB CSE2110 outcome 3.2 distinguishes: "functions (subprograms that return a value) and procedures (subprograms that do not return a value)."— 执行某些操作(打印、修改结构)但不产生输出值。示例:greet("Alice")只是打印;没有值返回供赋值。AB CSE2110 结果 3.2 区分:"函数(有返回值的子程序)和过程(无返回值的子程序)"。 - Function with return value有返回值的函数 — produces a result the caller can store or use directly.
SET x TO square(5)stores the return value 25 inx.RETURNalso exits the function immediately.— 产生调用方可以存储或直接使用的结果。SET x TO square(5)将返回值 25 存入x。RETURN也立即退出函数。 - Early return提前返回 — a RETURN inside an IF statement exits the function early. After the first RETURN that executes, the rest of the function body is skipped.— IF 语句内的 RETURN 提前退出函数。在第一个执行的 RETURN 之后,函数体的其余部分被跳过。
SET result TO my_function(args). If you call a value-returning function without capturing the result, the value is discarded.关键规则:如果需要返回值,务必捕获它:SET result TO my_function(args)。如果调用有返回值的函数时不捕获结果,值将被丢弃。
Problem: write a function that takes a score and returns the letter grade ("A", "B", "C", "D", or "F").问题:编写一个函数,接受分数并返回字母等级("A"、"B"、"C"、"D" 或 "F")。
Pseudocode with early returns.带提前返回的伪代码。
FUNCTION grade(score):
IF score >= 90 THEN RETURN "A"
IF score >= 80 THEN RETURN "B"
IF score >= 70 THEN RETURN "C"
IF score >= 60 THEN RETURN "D"
RETURN "F"
END FUNCTION
OUTPUT grade(95) -- "A"
OUTPUT grade(82) -- "B"
OUTPUT grade(55) -- "F"
说明:每个 RETURN 立即退出函数并将字符串返回给调用方。对于分数 82:第一个 IF(≥90)为假跳过;第二个 IF(≥80)为真,立即返回 "B",其余 IF 语句均不执行。这是返回值(return value,返回值)的典型用法。For score 82: first IF (≥90) is false, skip; second IF (≥80) is true, immediately return "B". The remaining IF statements never execute. This is the return value in action.
Python rendering.Python 实现。
def grade(score):
if score >= 90: return "A"
if score >= 80: return "B"
if score >= 70: return "C"
if score >= 60: return "D"
return "F"
print(grade(95)) # A
print(grade(82)) # B
print(grade(55)) # F
The caller uses the return value directly in print(). Alternatively: letter = grade(82) stores "B" in the variable letter.调用方在 print() 中直接使用返回值。或者:letter = grade(82) 将 "B" 存入变量 letter。
FUNCTION double(n): RETURN n * 2 when called as double(6)?FUNCTION double(n): RETURN n * 2 以 double(6) 调用时,返回值是多少?double(6), n is bound to 6. The function returns 6 * 2 = 12. The return value 12 is sent back to the caller.调用 double(6) 时,n 绑定到 6。函数返回 6 * 2 = 12。返回值 12 被传回调用方。n gets the argument value 6. The RETURN statement sends back n * 2 = 6 * 2 = 12.形参 n 获取实参值 6。RETURN 语句将 n * 2 = 6 * 2 = 12 传回。Going deeper — functions as expressions and composing calls深入 — 函数作为表达式与调用的组合
Because a value-returning function produces a value, you can use a call anywhere a value is expected. This means you can compose calls: OUTPUT double(square(3)) evaluates square(3) = 9 first, then passes 9 as the argument to double, giving 18. You can also use a return value in an arithmetic expression: SET total TO price(quantity) + tax(quantity). This composability is why functions are described as "first-class" building blocks in all of these curricula: Ontario ICS3U A3, AP CSP Big Idea 3 (AAP), BC CP11 "structures," and AB CSE2110 all treat functions as reusable computational units you combine like LEGO bricks. Composition is the heart of modular design (§6).因为有返回值的函数产生一个值,所以你可以在任何需要值的地方使用调用。这意味着你可以组合调用:OUTPUT double(square(3)) 首先计算 square(3) = 9,然后将 9 作为实参传递给 double,得到 18。你也可以在算术表达式中使用返回值:SET total TO price(quantity) + tax(quantity)。这种可组合性是为什么函数在所有这些大纲中被描述为"一等"构建块:安大略 ICS3U A3、AP CSP 大概念 3(AAP)、BC CP11"结构"和 AB CSE2110 都将函数视为可组合的可复用计算单元,就像乐高积木一样。组合是模块化设计(§6)的核心。
Variable Scope: Local vs Global变量作用域:局部变量与全局变量
- Local variable局部变量(local variable) — created inside a function. Only visible inside that function. Destroyed when the function returns. Two functions can each have a local variable called
totalwithout conflict.— 在函数内创建。只在该函数内可见。函数返回时销毁。两个函数各自都可以有名为total的局部变量,互不冲突。 - Global variable全局变量(global variable) — created outside all functions. Visible everywhere in the program. Changing it inside one function affects all other code that reads it. AB CSE2110 outcome 3.3 says to "analyze and determine the type of scope required."— 在所有函数外创建。在程序的所有地方可见。在一个函数内更改它会影响读取它的所有其他代码。AB CSE2110 结果 3.3 要求"分析并确定所需的作用域类型"。
- Best practice最佳实践 — prefer local variables. Pass data in via parameters and get data out via return values. Only use globals for constants or settings that genuinely need to be shared program-wide. Ontario ICS3U A3.2 explicitly says "appropriate variable scope (e.g., local, global)."— 优先使用局部变量。通过形参传入数据,通过返回值传出数据。只将全局变量用于真正需要程序范围内共享的常量或设置。安大略 ICS3U A3.2 明确要求"适当的变量作用域(如局部、全局)"。
Trace this program and predict the output for each print statement.追踪此程序,预测每个打印语句的输出。
Pseudocode.伪代码。
SET total TO 100 -- global variable (全局变量)
FUNCTION add_five():
SET total TO total + 5 -- local? or global?
RETURN total
END FUNCTION
OUTPUT total -- Line A
OUTPUT add_five() -- Line B
OUTPUT total -- Line C
Python rendering (Python requires the global keyword to modify a global).Python 实现(Python 需要 global 关键字才能修改全局变量)。
total = 100 # global variable (全局变量)
def add_five():
global total # must declare to modify the global
total = total + 5
return total
print(total) # Line A: 100
print(add_five()) # Line B: 105 (modifies the global)
print(total) # Line C: 105 (global was changed!)
Without global total inside the function, Python would create a new local variable called total, and the global would remain 100. This is exactly why unintended global modification is a common bug: the behaviour depends on one keyword. Prefer passing total as a parameter and returning the result instead.如果函数内没有 global total,Python 会创建一个名为 total 的新局部变量,全局变量仍为 100。这正是无意的全局变量修改成为常见错误的原因:行为取决于一个关键字。建议改为将 total 作为形参传入,并返回结果。
count. Can they interfere with each other?两个函数各自都有一个名为 count 的局部变量。它们会互相干扰吗?count each have their own independent count. Changing one does not affect the other. This isolation is the main benefit of local scope.局部变量与创建它们的函数隔离。两个函数各自都有名为 count 的局部变量,各自拥有独立的 count。更改一个不会影响另一个。这种隔离是局部作用域的主要优点。Going deeper — mutable global state and why it causes hard bugs Honors — ICS4U C1.3 / CSE2110深入 — 可变全局状态及其引发难以调试的错误 荣誉 — ICS4U C1.3 / CSE2110
When a function silently reads and writes a global variable, the function's behaviour depends on hidden state outside its parameters. This creates two problems: (1) Non-reproducibility — calling the function twice with the same arguments can produce different results if the global changed between calls. (2) Tight coupling — every function that touches the global becomes coupled to every other; changing the global's name, type, or range requires editing all of them. AB CSE2110 outcome 3.4 says to "analyze for, and maintain, an appropriate balance between the coupling or dependency and cohesion or focus of subprograms." Ontario ICS4U C1.3 ("functional decomposition in subprogram design") is assessed precisely on this. The fix is simple: pass the value as a parameter and return the new value — zero hidden state, zero coupling.当函数静默地读写全局变量时,函数的行为取决于其形参之外的隐藏状态。这带来两个问题:(1) 不可重现性——如果全局变量在两次调用之间发生了变化,用相同实参调用函数两次可能产生不同结果。(2) 紧耦合——所有触及全局变量的函数都与彼此耦合;更改全局变量的名称、类型或范围需要编辑所有这些函数。AB CSE2110 结果 3.4 要求"分析并维护子程序之间耦合(依赖)和内聚(专注度)的适当平衡"。安大略 ICS4U C1.3("子程序设计中的函数分解")正是针对这一点进行评估。解决方法很简单:将值作为形参传入,将新值作为返回值传出——零隐藏状态,零耦合。
Modular Design: Decomposing a Program into Functions模块化设计:将程序分解为函数
- Single-responsibility rule单一职责规则 — every function should do exactly one thing, named by a verb-noun pair (e.g.,
get_scores,compute_average,letter_grade,display_report). AB CSE2110 outcome 3.4: "appropriate balance between coupling … and cohesion."— 每个函数应该只做一件事,用动词-名词组合命名(如get_scores、compute_average、letter_grade、display_report)。AB CSE2110 结果 3.4:"耦合……与内聚的适当平衡"。 - Top-down design自顶向下设计 — start with the main function (high level); each step becomes a function call; implement each sub-function; repeat. ICS3U B2.3: "apply the principle of modularity to design reusable code." CSTA 3A-AP-17: "using constructs such as procedures, modules."— 从主函数(高层)开始;每个步骤变成一个函数调用;实现每个子函数;重复。ICS3U B2.3:"应用模块化原则设计可复用代码。" CSTA 3A-AP-17:"使用过程、模块等构造"。
- Independently testable可独立测试 — you can test
compute_average([80, 90, 70])alone before hooking it up to the rest. Isolating bugs becomes trivial.— 你可以在将compute_average([80, 90, 70])连接到其余部分之前单独测试它。隔离错误变得轻而易举。
Problem: a program reads 5 scores, computes the average, determines the letter grade (A/B/C/D/F), and displays a report. Decompose into functions.问题:程序读取 5 个成绩,计算平均分,确定字母等级(A/B/C/D/F),并显示报告。分解为函数。
Decomposition into four functions.分解为四个函数。
FUNCTION get_scores():
SET scores TO empty list
FOR i FROM 1 TO 5:
INPUT score
APPEND score TO scores
RETURN scores
END FUNCTION
FUNCTION compute_average(scores):
SET total TO 0
FOR EACH s IN scores: SET total TO total + s
RETURN total / 5
END FUNCTION
FUNCTION letter_grade(average):
IF average >= 90 THEN RETURN "A"
IF average >= 80 THEN RETURN "B"
IF average >= 70 THEN RETURN "C"
IF average >= 60 THEN RETURN "D"
RETURN "F"
END FUNCTION
FUNCTION display_report(avg, grade):
OUTPUT "Average: " + avg
OUTPUT "Grade: " + grade
END FUNCTION
-- Main program
SET scores TO get_scores()
SET avg TO compute_average(scores)
SET grade TO letter_grade(avg)
display_report(avg, grade)
说明:主程序(main program)只有四行,清晰如故事情节。每个函数(函数,function)只做一件事;可以单独测试每个函数。数据通过形参(parameter,形参)和返回值(return value,返回值)流动,无需全局变量(global variable,全局变量)。The main program is four lines — readable as a story. Each function does one thing; each can be tested in isolation. Data flows via parameters and return values, with no global variables needed.
Python rendering.Python 实现。
def get_scores():
scores = []
for i in range(5):
scores.append(float(input("Score: ")))
return scores
def compute_average(scores):
return sum(scores) / len(scores)
def letter_grade(average):
if average >= 90: return "A"
if average >= 80: return "B"
if average >= 70: return "C"
if average >= 60: return "D"
return "F"
def display_report(avg, grade):
print(f"Average: {avg:.1f}")
print(f"Grade: {grade}")
scores = get_scores()
avg = compute_average(scores)
grade = letter_grade(avg)
display_report(avg, grade)
get_scores(), compute_average(), then implement each sub-function. Each step in the main program becomes a function call. The main program stays readable; complexity lives in the sub-functions.在自顶向下设计中,你首先使用高层调用(如 get_scores()、compute_average())编写主函数,然后实现每个子函数。主程序中的每个步骤变成一个函数调用。主程序保持可读性;复杂性存在于子函数中。Built-in Functions and Libraries内置函数与库
- Built-in functions内置函数 — available without importing anything. Python examples:
len(),print(),input(),abs(),max(),min(),sum(),round(),range(),int(),float(),str().— 无需导入即可使用。Python 示例:len()、print()、input()、abs()、max()、min()、sum()、round()、range()、int()、float()、str()。 - Standard library modules标准库模块 — import with
import module_name, then callmodule_name.function(). Examples:import mathgivesmath.sqrt(),math.floor(),math.pi;import randomgivesrandom.randint(). BC CP11 Content: "pre-built libraries and their documentation."— 用import module_name导入,然后调用module_name.function()。示例:import math提供math.sqrt()、math.floor()、math.pi;import random提供random.randint()。BC CP11 内容:"预建库及其文档"。 - Reading documentation阅读文档 — every library function has a signature (its name, parameters, return type) and a description. You do not need to see the implementation — only the interface. Ontario ICS3U A3.1: "use existing subprograms (e.g., random number generator, substring, absolute value) within computer programs."— 每个库函数都有签名(名称、形参、返回类型)和说明。你不需要看到实现——只需了解接口。安大略 ICS3U A3.1:"在计算机程序中使用现有子程序(如随机数生成器、子字符串、绝对值)"。
Problem: write a short program that (a) computes the hypotenuse of a right triangle with legs 3 and 4, and (b) rolls a six-sided die (random integer 1–6).问题:编写一个短程序,(a) 计算腿长为 3 和 4 的直角三角形的斜边,(b) 掷一个六面骰子(随机整数 1–6)。
Pseudocode (using library notation).伪代码(使用库表示法)。
-- (a) hypotenuse
SET hyp TO math.sqrt(3*3 + 4*4)
OUTPUT hyp -- 5.0
-- (b) dice roll
SET roll TO random.randint(1, 6)
OUTPUT roll -- a random integer between 1 and 6 inclusive
说明:math.sqrt() 和 random.randint() 是库(library,库)中的内置函数(built-in function,内置函数)。调用方只需知道接口(名称、参数、返回值),不需要知道内部实现——这就是抽象(abstraction,抽象)的体现。Callers only need the interface (name, parameters, return value), not the implementation — this is abstraction in action.
Python rendering.Python 实现。
import math
import random
# (a) hypotenuse 斜边
hyp = math.sqrt(3**2 + 4**2)
print(f"Hypotenuse: {hyp}") # 5.0
# (b) dice roll 骰子
roll = random.randint(1, 6)
print(f"Rolled: {roll}")
The import statement loads the module; after that, every function in the module is callable using module.function() syntax. BC CP11 says "pre-built libraries and their documentation" — you should know how to read the Python docs to find the signature of any built-in.import 语句加载模块;之后,模块中的所有函数都可以用 module.function() 语法调用。BC CP11 要求"预建库及其文档"——你应该知道如何阅读 Python 文档来查找任何内置函数的签名。
math.sqrt()?在 Python 中,使用 math.sqrt() 之前必须写什么?import module_name. After import math, you can call math.sqrt(), math.floor(), math.pi, and all other functions in the math module.在 Python 中,使用 import module_name 导入标准库模块。在 import math 之后,你可以调用 math.sqrt()、math.floor()、math.pi 以及 math 模块中的所有其他函数。import. use and require are keywords in other languages; include is used in C/C++. Only import math works in Python.Python 加载模块的关键字是 import。use 和 require 是其他语言的关键字;include 用于 C/C++。只有 import math 在 Python 中有效。abs() is a Python built-in function — no import needed. abs(-7) returns 7. It is available the same way print() and len() are, without any import statement.abs() 是 Python 内置函数——无需导入。abs(-7) 返回 7。它与 print() 和 len() 一样可用,无需任何 import 语句。abs() is a built-in (no import). math.abs() does not exist in Python's math module. absolute() and Math.abs() are not valid Python (the latter is JavaScript/Java).abs() 是内置函数(无需导入)。math.abs() 在 Python 的 math 模块中不存在。absolute() 和 Math.abs() 不是有效的 Python(后者是 JavaScript/Java)。Going deeper — reading library documentation and writing docstrings深入 — 阅读库文档和编写文档字符串
Every professional library ships with documentation that follows the same pattern: the function's signature (name, parameters, types, return type), a short description, and examples. For Python's random.randint(a, b), the docs say: "Return a random integer N such that a <= N <= b." That one sentence tells you everything you need to call the function correctly. You should write the same kind of documentation for your own functions using Python's docstring convention: a triple-quoted string immediately after the def line. BC CP11 "pre-built libraries and their documentation" assesses this skill. ICS3U A3.1 implicitly requires you to find and read existing subprogram documentation. Alberta CSE2110 outcome 1.1.4 says a benefit of modular programming is "improving the readability of a program" — a good docstring is the simplest form of readability improvement. Example:每个专业库都附带遵循相同模式的文档:函数的签名(名称、形参、类型、返回类型)、简短描述和示例。对于 Python 的 random.randint(a, b),文档说:"返回一个随机整数 N,使得 a <= N <= b。"这一句话告诉你正确调用该函数所需的一切。你应该使用 Python 的文档字符串约定为自己的函数编写同类文档:在 def 行之后立即写一个三引号字符串。BC CP11"预建库及其文档"考查这项技能。ICS3U A3.1 隐含要求你找到并阅读现有子程序文档。阿尔伯塔 CSE2110 结果 1.1.4 指出模块化编程的好处之一是"提高程序的可读性"——好的文档字符串是最简单的可读性改进形式。示例:
def compute_average(scores):
"""Return the arithmetic mean of a list of numbers.
计算数字列表的算术平均值。
Args:
scores: list of numeric values (数字列表)
Returns:
float: the mean (平均值,浮点数)
"""
return sum(scores) / len(scores)
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- Name the function and list its parameters before writing the body.在编写函数体之前先命名函数并列出形参。 On any exam question that asks you to write a function, start with the signature:
FUNCTION name(param1, param2). This forces you to identify the inputs and clarifies what the function promises to do. Then write the body; then write the RETURN statement last.在任何要求你编写函数的考试题中,从签名开始:FUNCTION name(param1, param2)。这迫使你识别输入并明确函数承诺做什么。然后编写函数体;最后写 RETURN 语句。 - Trace your function with a concrete call before submitting.提交前用具体调用追踪你的函数。 Pick one argument value, trace the function body step by step, and verify the return matches the expected output. A 60-second trace catches most off-by-one and wrong-operator bugs.选一个实参值,逐步追踪函数体,验证返回值是否符合预期输出。60 秒的追踪能发现大多数"差一"和运算符错误。
- Parameter vs argument — always use the right word.形参与实参——始终使用正确的词。 On Ontario ICS3U A3.2 and AB CSE2110 questions, examiners specifically check whether you can distinguish parameters (in the definition) from arguments (at the call site). Saying "the function takes two parameters" and "I pass two arguments" is precise; saying "inputs" for both loses marks.在安大略 ICS3U A3.2 和 AB CSE2110 题目中,考官会专门检查你是否能区分形参(定义中)和实参(调用处)。说"函数接受两个形参"和"我传递两个实参"是准确的;两者都说"输入"会失分。
- For a scope question, always label local vs global.对于作用域问题,始终标注局部变量与全局变量。 When tracing a program with both global and local variables, draw two separate columns or sections: one for the global state and one for the current function's local state. Show them separately; examiners award marks for correctly showing that the local variable does not affect the global (or vice versa).当追踪同时包含全局变量和局部变量的程序时,画两个独立的列或区域:一个表示全局状态,一个表示当前函数的局部状态。分开显示;考官会对正确显示局部变量不影响全局变量(反之亦然)的答案给分。
- Name each sub-function with a verb-noun pair.用动词-名词对命名每个子函数。 On CSTA 3A-AP-17 / 3A-AP-18 and ICS3U B2.3 questions about modular design, explicitly name each function. "A function that gets the scores, a function that computes the average, a function that determines the grade" — with names like
get_scores,compute_average,letter_grade— scores higher than vague descriptions.在关于模块化设计的 CSTA 3A-AP-17 / 3A-AP-18 和 ICS3U B2.3 题目中,明确命名每个函数。"一个获取成绩的函数、一个计算平均值的函数、一个确定等级的函数"——配以如get_scores、compute_average、letter_grade的名称——比模糊描述得分更高。 - Show data flow: what goes in, what comes out.展示数据流:进什么,出什么。 For each function in your modular design, state the parameters (input data) and return value (output data). This demonstrates you understand the interface, not just the name.对于模块化设计中的每个函数,说明形参(输入数据)和返回值(输出数据)。这表明你理解接口,而不仅仅是名称。
- Use pseudocode keywords for function definition questions.函数定义题使用伪代码关键字。 AP CSP uses
PROCEDURE name(params) { ... }andRETURN(value). The generic pseudocode isFUNCTION name(params): ... RETURN value. In Python it isdef name(params): ... return value. Know all three; use the one the question specifies.AP CSP 使用PROCEDURE name(params) { ... }和RETURN(value)。通用伪代码是FUNCTION name(params): ... RETURN value。Python 中是def name(params): ... return value。了解所有三种;使用题目指定的那种。 - Distinguish procedures from functions on AB and ON exams.在 AB 和 ON 考试中区分过程和函数。 AB CSE2110 outcome 3.2 specifically tests the difference: a function returns a value; a procedure does not. When a question says "write a procedure to display the result," do not add a RETURN statement.AB CSE2110 结果 3.2 专门考查这一区别:函数有返回值;过程没有。当题目说"编写一个过程来显示结果"时,不要添加 RETURN 语句。
Flashcards闪卡
def f(n), n is a parameter. In f(7), 7 is an argument.形参(parameter)= 定义中的变量(占位符)。实参(argument)= 调用处的实际值。在 def f(n) 中,n 是形参。在 f(7) 中,7 是实参。x = square(5) stores 25 in x. RETURN also exits the function immediately.由 RETURN / return 语句传回调用方的值。调用方可以存储它:x = square(5) 将 25 存入 x。RETURN 也立即退出函数。total without conflict.在函数内部创建。只在该函数内可见。函数返回时销毁。两个函数各自可以有名为 total 的局部变量,互不冲突。import. Example: import math gives math.sqrt(). BC CP11: "pre-built libraries and their documentation." CSTA 3B-AP-16: code reuse via libraries.预编写函数的集合。用 import 使用。示例:import math 提供 math.sqrt()。BC CP11:"预建库及其文档"。CSTA 3B-AP-16:通过库实现代码复用。len(), print(), input(), abs(), max(), min(), sum(), round(), range(), int(), float(), str().在 Python 中无需导入即可使用:len()、print()、input()、abs()、max()、min()、sum()、round()、range()、int()、float()、str()。Practice Quiz综合测验
FUNCTION triple(n): RETURN n * 3 END FUNCTION when called as triple(4)?FUNCTION triple(n): RETURN n * 3 END FUNCTION 以 triple(4) 调用时,返回值是多少?4 * 3 = 12.实参 4 绑定到形参 n。函数返回 4 * 3 = 12。x = 10 (global). Inside a function, x = x + 5 runs (without declaring global). What is the global x after the function returns?已知:x = 10(全局)。在函数内部,x = x + 5 运行(未声明 global)。函数返回后全局变量 x 是多少?global x inside the function, Python creates a new local variable x. The assignment modifies the local, not the global. The global x remains 10.在函数内没有 global x,Python 创建一个新的局部变量 x。赋值修改的是局部变量,而非全局变量。全局 x 仍为 10。global x, Python's assignment creates a local variable. The global is unchanged. This is why modifying globals inside functions requires explicit declaration.没有 global x,Python 的赋值创建一个局部变量。全局变量不变。这就是为什么在函数内修改全局变量需要显式声明。import math allow you to do?import math 允许你做什么?import math loads Python's math module, giving access to pre-built functions like math.sqrt(), math.floor(), math.ceil(), and constants like math.pi. BC CP11: "pre-built libraries and their documentation."import math 加载 Python 的 math 模块,提供对预建函数(如 math.sqrt()、math.floor()、math.ceil())和常量(如 math.pi)的访问。BC CP11:"预建库及其文档"。import loads an existing module; it does not define a new one or restrict usage. After import, the module's functions are available anywhere in the file.import 加载现有模块;不定义新模块或限制使用。导入后,模块的函数在文件的任何地方都可用。FUNCTION greet(name): OUTPUT "Hi " + name, what kind of subprogram is this? 🇨🇦 AB CSE2110在函数 FUNCTION greet(name): OUTPUT "Hi " + name 中,这是哪种子程序?🇨🇦 AB CSE2110Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Define a function in pseudocode and in Python that takes two parameters, computes a result, and returns it. State the function definition keyword, the parameter list, the body, and the RETURN statement. 🇺🇸 CSTA 3A-AP-18 / 🇨🇦 ON ICS3U A3.2用伪代码和 Python 定义一个接受两个形参、计算结果并返回的函数。说明函数定义关键字、形参列表、函数体和 RETURN 语句。🇺🇸 CSTA 3A-AP-18 / 🇨🇦 ON ICS3U A3.2
- Distinguish parameters from arguments: given a function definition and a call, identify which variables are parameters and which values are arguments. 🇨🇦 AB CSE2110 outcome 3.3 / ON ICS3U A3.2区分形参(parameter)和实参(argument):给定函数定义和调用,识别哪些变量是形参,哪些值是实参。🇨🇦 AB CSE2110 结果 3.3 / ON ICS3U A3.2
- Distinguish a value-returning function from a procedure (void function): state what the RETURN statement does and identify whether a given function definition has one. 🇨🇦 AB CSE2110 outcome 3.2区分有返回值函数和过程(无返回值函数):说明 RETURN 语句的作用,并识别给定函数定义是否有 RETURN 语句。🇨🇦 AB CSE2110 结果 3.2
- Trace a function call with concrete argument values: show the parameter binding, step through the body, and identify the return value. Use a variable trace table. 🇨🇦 ON ICS3U A3 / AB CSE2110用具体实参值追踪函数调用:展示形参绑定,逐步执行函数体,确定返回值。使用变量追踪表。🇨🇦 ON ICS3U A3 / AB CSE2110
- Explain local scope vs global scope: for a given program, identify which variables are local and which are global, and predict what happens when a function modifies a local variable with the same name as a global. 🇨🇦 ON ICS3U A3.2 / AB CSE2110 outcome 3.3解释局部作用域与全局作用域:对于给定程序,识别哪些变量是局部的,哪些是全局的,并预测当函数修改与全局变量同名的局部变量时会发生什么。🇨🇦 ON ICS3U A3.2 / AB CSE2110 结果 3.3
- Apply modular design to a medium-complexity problem: name at least three functions using verb-noun pairs, state the parameters and return type of each, and show how the main program calls them in sequence. 🇨🇦 ON ICS3U B2.3 / AB CSE2110 outcome 3.4将模块化设计应用于中等复杂度的问题:用动词-名词对命名至少三个函数,说明每个函数的形参和返回类型,并展示主程序如何按顺序调用它们。🇨🇦 ON ICS3U B2.3 / AB CSE2110 结果 3.4
- Use a built-in function (e.g.,
abs(),len(),max()) and a standard library function (e.g.,math.sqrt(),random.randint()) correctly in a program. State the purpose ofimport. 🇨🇦 ON ICS3U A3.1 / 🇨🇦 BC CP11在程序中正确使用内置函数(如abs()、len()、max())和标准库函数(如math.sqrt()、random.randint())。说明import的作用。🇨🇦 ON ICS3U A3.1 / 🇨🇦 BC CP11 - Explain procedural abstraction: state why a caller only needs to know the function's interface (name, parameters, return type) and not its implementation. Give an example. 🇺🇸 AP CSP AAP-3.B / 🇨🇦 BC CP12解释过程抽象:说明为什么调用方只需知道函数的接口(名称、形参、返回类型)而不需要知道其实现。举一个例子。🇺🇸 AP CSP AAP-3.B / 🇨🇦 BC CP12
- State verbatim (or near-verbatim) CSTA 3A-AP-17 and 3A-AP-18, and explain how each maps to the concept of functions and modular design. 🇺🇸 CSTA Level 3A逐字(或近逐字)陈述 CSTA 3A-AP-17 和 3A-AP-18,并解释每个标准如何映射到函数与模块化设计的概念。🇺🇸 CSTA Level 3A
- State verbatim (or near-verbatim) Ontario ICS3U A3.2, and explain what "parameter passing" and "appropriate variable scope" mean in the context of a function you write. 🇨🇦 ON ICS3U A3.2逐字(或近逐字)陈述安大略 ICS3U A3.2,并解释"参数传递"和"适当的变量作用域"在你编写的函数上下文中的含义。🇨🇦 ON ICS3U A3.2
- Honors — ICS4U C1.3 / CSE2110 / BC CP12 Explain the hazards of mutable global state in a modular program: describe what "coupling" means, why modifying globals inside functions increases coupling, and how using parameters and return values eliminates the problem. 🇨🇦 ICS4U C1.3 / AB CSE2110 outcome 3.4荣誉 — ICS4U C1.3 / CSE2110 / BC CP12 解释模块化程序中可变全局状态的危害:描述"耦合"的含义,为什么在函数内修改全局变量会增加耦合,以及如何使用形参和返回值消除这个问题。🇨🇦 ICS4U C1.3 / AB CSE2110 结果 3.4
What This Feeds Into本单元的去向
Functions and modular design is the hinge unit in this HS Computer Science series: everything before it (computational thinking, variables, control flow) feeds into it as prerequisite; everything after it (data structures, OOP, software development) assumes you can write and call functions fluently. The two downstream AP courses both depend on procedural abstraction. The link below points at the existing AP CSA guide where methods (Java's term for functions) appear from Unit 1 onwards.函数与模块化设计是本 HS 计算机科学系列中的枢纽单元:此前的所有内容(计算思维、变量、控制流)作为先决条件汇入此单元;此后的所有内容(数据结构、OOP、软件开发)都假定你能流利地编写和调用函数。两门下游 AP 课程都依赖过程抽象。以下链接指向现有 AP CSA 指南,其中方法(Java 中函数的术语)从 Unit 1 开始出现。
Within High School Computer Science.在 HS Computer Science 内部。
The Data Structures guide (Unit 5) assumes you can write functions that accept and return lists. The OOP guide (Unit 8) builds on modular design: an object's methods are functions scoped to the object. The Software Development Process guide shows how the function-per-sub-problem discipline (top-down design) scales to real software projects. The Searching and Sorting guide calls library functions and passes comparison functions as arguments — both topics require the fluency built here.数据结构指南(Unit 5)假定你能编写接受和返回列表的函数。OOP 指南(Unit 8)以模块化设计为基础:对象的方法是作用域限于对象的函数。软件开发过程指南展示了每个子问题一个函数的原则(自顶向下设计)如何扩展到真实软件项目。搜索与排序指南调用库函数并将比较函数作为实参传递——这两个主题都需要此处建立的流利度。
AP feeder links (existing in this repo).AP 衔接链接(本仓库中已有)。
AP CSP Big Idea 3 topics 3.12–3.14 (Calling Procedures, Developing Procedures, Libraries) directly test the concepts in this guide and account for a significant portion of the 30–35% AAP exam band. AP CSA (Java-specific) uses methods everywhere from Unit 1; the parameter-passing, return-value, and scope concepts taught here are identical to how Java methods work. Mastering this unit before starting either AP course eliminates the single most common source of confusion in introductory programming.AP CSP 大概念 3 主题 3.12–3.14(调用过程、开发过程、库)直接考查本指南中的概念,占 30–35% AAP 考试段的重要比例。AP CSA(Java 专项)从 Unit 1 起处处使用方法;此处教授的参数传递、返回值和作用域概念与 Java 方法的工作方式完全相同。在开始任一 AP 课程之前掌握本单元,可以消除入门编程中最常见的困惑来源。