High School Computer Science

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 演示。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Pseudocode + Python worked examples伪代码 + 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.找到所在行后,用下面两张卡片决定推进速度。

!
If you are cramming the night before如果你在临阵磨枪

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.背熟四件事:函数是什么以及为何需要它;如何用伪代码定义和调用函数;形参是什么以及返回值是什么;局部作用域与全局作用域的区别。读每个速记框,跳过深入框。

*
If you are going for the top mark如果你目标顶分

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 要求你编写具有参数传递和正确作用域的函数。这两项技能本指南均完整涵盖。

Scope and purity note.作用域与纯函数说明。 Section 5 (Variable Scope) covers local vs global variables at the assessed level for all four curricula. The going-deeper box discusses the hazards of mutable global state — a concept that maps to Ontario ICS4U C1.3 functional decomposition and AB CSE2110 outcome 3.3.3. For floor students (ICS3U, AP CSP, BC CP11), the rule "prefer local variables; avoid writing to globals inside functions" is the take-away. The Honors box shows why that rule exists.§5(变量作用域)在四套大纲的考查层次上涵盖局部变量与全局变量。深入框讨论可变全局状态的风险——该概念对应安大略 ICS4U C1.3 函数分解和 AB CSE2110 结果 3.3.3。对于基础学生(ICS3U、AP CSP、BC CP11),"优先使用局部变量;避免在函数内写入全局变量"是要点。荣誉框解释该规则存在的原因。

Why Functions? Reuse and Abstraction为什么要用函数?复用与抽象

Three reasons to use a function — memorise these.使用函数的三个理由 — 背熟这些。
  • 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:"通过使用过程、模块等构造将问题分解为更小的组件。"
The one fact that catches people: a function is an abstraction, not just a shortcut. When you call 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) 时,你不需要知道内部算法——只需信任接口。构建自己的函数,就能给调用者带来同样的好处。
WE
Worked Example 1 · From repeated code to a function例题 1 · 从重复代码到函数

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:"应用模块化原则设计可复用代码。"

A student copies the same 10-line calculation into five different parts of their program. What is the main problem with this approach?一名学生将同一段 10 行计算复制到程序的五个不同部分。这种做法的主要问题是什么?
§1 · Q1
The program will run more slowly程序运行会更慢
Python does not allow duplicate codePython 不允许重复代码
If the logic needs to change, all five copies must be updated, creating maintenance risk如果逻辑需要更改,必须更新所有五处副本,造成维护风险
The program will use more memory程序会使用更多内存
Duplicated code means any bug fix or change must be applied to every copy. Missing even one creates inconsistency. Functions solve this by keeping the logic in one place. CSTA 3A-AP-18 encourages using procedures to avoid exactly this problem.重复代码意味着任何错误修复或更改都必须应用到每个副本。漏掉一处就会造成不一致。函数通过将逻辑保存在一处来解决这个问题。CSTA 3A-AP-18 鼓励使用过程来避免此类问题。
The primary issue is maintainability: five copies mean five places to update. Functions solve this by centralising the logic. Speed and memory impact are negligible for a 10-line block.主要问题是可维护性:五个副本意味着五处需要更新。函数通过集中逻辑来解决这个问题。对于 10 行代码块,速度和内存影响可忽略不计。
Which AP CSP Learning Objective says "Use abstraction to manage complexity in a program"?哪个 AP CSP 学习目标说"使用抽象管理程序中的复杂性"?
§1 · Q2
AAP-3.B
AAP-4.A
DAT-1.A
CRD-2.A
AAP-3.B (verbatim): "Use abstraction to manage complexity in a program." This is the Learning Objective for procedural abstraction in AP CSP Big Idea 3. It maps directly to defining and calling functions/procedures.AAP-3.B(原文):"使用抽象管理程序中的复杂性。"这是 AP CSP 大概念 3 中过程抽象的学习目标。它直接对应定义和调用函数/过程。
AAP-4.A is about algorithm efficiency. DAT-1.A is about data representation. CRD-2.A is about program design. AAP-3.B is the abstraction and procedures LO.AAP-4.A 关于算法效率。DAT-1.A 关于数据表示。CRD-2.A 关于程序设计。AAP-3.B 是抽象和过程的学习目标。
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定义与调用函数

Two halves of a function — know both.函数的两个部分 — 两者都要掌握。
  • 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 just name(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)。程序跳入函数体,执行后返回调用处。
Execution flow: definition happens at load time (not run time). Each call jumps into the function, runs it to completion (or to a RETURN statement), then execution continues from the line after the call. AB CSE2110 outcome 3.2 says to "use appropriate types of subprograms … functions." Ontario ICS3U A3.2 says to "write subprograms … to perform tasks within programs."执行流程:定义在加载时发生(不是运行时)。每次调用跳入函数,运行到结束(或 RETURN 语句),然后继续执行调用之后的那行。AB CSE2110 结果 3.2 要求"使用适当类型的子程序……函数"。安大略 ICS3U A3.2 要求"编写子程序……在程序中执行任务"。
WE
Worked Example 2 · Defining and calling a greeting function例题 2 · 定义和调用问候函数

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

When does the code inside a function definition run?函数定义内部的代码何时运行?
§2 · Q1
As soon as the FUNCTION line is reached一旦到达 FUNCTION 行就立即运行
Only when the function is called只有在函数被调用时
At the end of the program在程序结束时
When the file is imported当文件被导入时
Defining a function stores the code but does not execute it. The code inside runs only when the function is called (invoked). This is why you can define a function before you know what arguments will be passed.定义函数会存储代码但不执行它。内部代码只在函数被调用时运行。这就是为什么你可以在知道将传递哪些实参之前定义函数。
The FUNCTION line registers the function's name and code; execution only happens at the call site. Think of a function definition as writing a recipe and a call as cooking it.FUNCTION 行注册函数的名称和代码;执行只在调用处发生。把函数定义想象成写食谱,调用想象成按食谱烹饪。
In Python, which keyword begins a function definition?在 Python 中,哪个关键字开始函数定义?
§2 · Q2
function
PROCEDURE
define
def
Python uses 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
In Python, the keyword is def (short for define), not function or define. PROCEDURE is the AP CSP pseudocode keyword.在 Python 中,关键字是 def(define 的缩写),而不是 functiondefinePROCEDURE 是 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 vs argument — different words, different moments.形参与实参 — 不同的词,不同的时刻。
  • 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), width and height are parameters.— 函数定义中的变量名。它是占位符:有名称但在函数被调用之前没有值。在 FUNCTION area(width, height) 中,widthheight 是形参。
  • Argument实参(argument) — the actual value passed at the call site. In area(5, 3), 5 and 3 are arguments. At call time, width gets 5 and height gets 3.— 在调用处传递的实际值。在 area(5, 3) 中,53 是实参。调用时,width 得到 5height 得到 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 涵盖"单向和双向参数传递"。
Memory trick: Parameters live in the function definition; Arguments are the actual values at the call. Ontario ICS3U A3.2 says "write subprograms … that use parameter passing."记忆技巧:参存在于函数定义中;参是调用处的实际值。安大略 ICS3U A3.2 要求"编写……使用参数传递的子程序"。
WE
Worked Example 3 · A function with two parameters例题 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

说明:baseexponent 是形参(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.每次调用都会创建 baseexponent 的新副本,并绑定给定的实参值。在函数内更改 result 不会影响函数外的任何变量——这就是单向参数传递的实际效果。

In FUNCTION square(n): RETURN n * n, what is n?FUNCTION square(n): RETURN n * n 中,n 是什么?
§3 · Q1
A parameter — a placeholder in the definition形参(parameter)——定义中的占位符
An argument — the actual value passed at call time实参(argument)——调用时传递的实际值
A return value返回值(return value)
A global variable全局变量(global variable)
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 = 7square(9) 绑定 n = 9
Parameters are in the definition; arguments are at the call site. n is in the definition — it is a parameter. The return value is n * n.形参在定义中;实参在调用处。n 在定义中——它是形参。返回值是 n * n
A function is defined as FUNCTION add(a, b): RETURN a + b. What is the result of add(4, 7)?函数定义为 FUNCTION add(a, b): RETURN a + badd(4, 7) 的结果是什么?
§3 · Q2
4
7
11
47
At the call 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
Arguments bind in order: a = 4, b = 7. The return value is a + b = 4 + 7 = 11.实参按顺序绑定:a = 4b = 7。返回值是 a + b = 4 + 7 = 11

Return Values返回值

RETURN sends a value out of the function back to the caller.RETURN 将值从函数传回调用方。
  • 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 in x. RETURN also exits the function immediately.— 产生调用方可以存储或直接使用的结果。SET x TO square(5) 将返回值 25 存入 xRETURN 也立即退出函数。
  • 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 之后,函数体的其余部分被跳过。
Key rule: always capture the return value if you need it: 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)。如果调用有返回值的函数时不捕获结果,值将被丢弃。
WE
Worked Example 4 · A grade classifier function with early return例题 4 · 带提前返回的成绩分类函数

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

What is the return value of FUNCTION double(n): RETURN n * 2 when called as double(6)?FUNCTION double(n): RETURN n * 2double(6) 调用时,返回值是多少?
§4 · Q1
6
12
2
Nothing — the function has no output没有——函数没有输出
At call 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 被传回调用方。
The parameter n gets the argument value 6. The RETURN statement sends back n * 2 = 6 * 2 = 12.形参 n 获取实参值 6。RETURN 语句将 n * 2 = 6 * 2 = 12 传回。
A function that prints output but has no RETURN statement is called a…一个打印输出但没有 RETURN 语句的函数称为……
§4 · Q2
Procedure / void function过程 / 无返回值函数(procedure / void function)
Value-returning function有返回值函数(value-returning function)
Parameter形参(parameter)
Library库(library)
AB CSE2110 outcome 3.2 distinguishes functions (return a value) from procedures (do not return a value). A function that only prints is a procedure or void function — it does work but sends nothing back to the caller.AB CSE2110 结果 3.2 区分函数(有返回值)和过程(无返回值)。只打印的函数是过程或无返回值函数——它执行工作但不向调用方传回任何值。
No RETURN = procedure (void). A value-returning function uses a RETURN statement to send a result back. Parameters are inputs; libraries are collections of pre-built functions.没有 RETURN = 过程(void)。有返回值函数使用 RETURN 语句将结果传回。形参是输入;库是预建函数的集合。
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变量作用域:局部变量与全局变量

Scope = which parts of the code can see (read/write) a variable.作用域 = 代码的哪些部分可以访问(读/写)一个变量。
  • 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 total without 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 明确要求"适当的变量作用域(如局部、全局)"。
Scope rule summary: Local beats global inside a function. If a local variable and a global variable have the same name, code inside the function sees the local one. Code outside the function sees the global one.作用域规则摘要:在函数内部,局部变量优先于全局变量。如果局部变量和全局变量同名,函数内部的代码看到的是局部变量;函数外部的代码看到的是全局变量。
WE
Worked Example 5 · Tracing local vs global scope例题 5 · 追踪局部作用域与全局作用域

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 作为形参传入,并返回结果。

A variable created inside a function is called a __________ and is only visible __________ .在函数内部创建的变量称为 __________,只在 __________ 可见。
§5 · Q1
global variable / inside the function and in the main program全局变量(global variable)/ 函数内部和主程序中
parameter / inside the function and at the call site形参(parameter)/ 函数内部和调用处
return value / after the RETURN statement返回值(return value)/ RETURN 语句之后
local variable / inside that function only局部变量(local variable)/ 只在该函数内部
A variable created inside a function is a local variable. It is only visible inside that function, and it is destroyed when the function returns. Ontario ICS3U A3.2 specifies "appropriate variable scope (e.g., local, global)."在函数内部创建的变量是局部变量(local variable)。它只在该函数内可见,函数返回时销毁。安大略 ICS3U A3.2 规定"适当的变量作用域(如局部、全局)"。
Local variables are scoped to the function they are created in. Global variables live outside all functions and are visible everywhere. Parameters are placeholders for input, not regular variables.局部变量的作用域限于创建它的函数。全局变量存在于所有函数之外,在任何地方都可见。形参是输入的占位符,不是普通变量。
Two functions each have a local variable named count. Can they interfere with each other?两个函数各自都有一个名为 count 的局部变量。它们会互相干扰吗?
§5 · Q2
Yes — they both write to the same memory location会——它们都写入同一内存位置
No — each function's local variables are independent; same name is fine不会——每个函数的局部变量是独立的;同名没有问题
Only if the functions call each other只有在函数互相调用时才会
Yes — Python does not allow two variables with the same name会——Python 不允许两个变量同名
Local variables are isolated to the function that creates them. Two functions with a local variable called 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。更改一个不会影响另一个。这种隔离是局部作用域的主要优点。
Local variables are isolated per function. The same name in two different functions refers to two completely separate storage locations. Only globals (or shared mutable objects) can create this kind of interference.局部变量按函数隔离。两个不同函数中的相同名称指向两个完全独立的存储位置。只有全局变量(或共享的可变对象)才能造成这种干扰。
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模块化设计:将程序分解为函数

Modular design = give each function one clear job; connect them via calls.模块化设计 = 让每个函数只做一件明确的事;通过调用连接它们。
  • 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_scorescompute_averageletter_gradedisplay_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]) 连接到其余部分之前单独测试它。隔离错误变得轻而易举。
BC CP11 names "structures" and "ways to modify existing code to meet a particular purpose" as core content — modular design is exactly that pattern.BC CP11 将"结构"和"修改现有代码以满足特定目的的方法"列为核心内容——模块化设计正是这种模式。
WE
Worked Example 6 · A grade-book program in four functions例题 6 · 用四个函数实现成绩册程序

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)
According to the single-responsibility rule, a function should…根据单一职责规则,函数应该……
§6 · Q1
Be as short as possible (ideally one line)尽可能短(理想情况下只有一行)
Never use parameters从不使用形参
Do exactly one clearly-named task只做一件命名清晰的任务
Always return a numeric value总是返回数值
The single-responsibility rule says each function should do exactly one thing, named by a clear verb-noun pair. This makes the function testable, reusable, and easy to understand. AB CSE2110 describes this as "cohesion" — a function with a single clear focus.单一职责规则要求每个函数只做一件事,用清晰的动词-名词组合命名。这使函数可测试、可复用且易于理解。AB CSE2110 将此描述为"内聚"——具有单一明确关注点的函数。
Single responsibility is about focus, not length. A function can be many lines long and still have a single responsibility. Length and parameter usage are separate concerns.单一职责是关于关注点,而不是长度。函数可以有很多行,但仍然只有一个职责。长度和形参使用是独立的关注点。
In top-down design, what does each step in the main function become?在自顶向下设计中,主函数中的每个步骤变成什么?
§6 · Q2
A global variable一个全局变量
A comment in the code代码中的注释
A new file一个新文件
A function call to a sub-function you then implement一个函数调用,然后你再实现该子函数
In top-down design, you write the main function first using high-level calls like 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())编写主函数,然后实现每个子函数。主程序中的每个步骤变成一个函数调用。主程序保持可读性;复杂性存在于子函数中。
Top-down design turns each high-level step into a function call, then you implement the called functions. This keeps the main program simple and lets you work on one function at a time.自顶向下设计将每个高层步骤转变为函数调用,然后你再实现被调用的函数。这使主程序简单,让你一次专注于一个函数。

Built-in Functions and Libraries内置函数与库

A library is a collection of pre-written functions you can call without defining them yourself.库是预编写函数的集合,你可以直接调用,无需自己定义。
  • 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 call module_name.function(). Examples: import math gives math.sqrt(), math.floor(), math.pi; import random gives random.randint(). BC CP11 Content: "pre-built libraries and their documentation."— 用 import module_name 导入,然后调用 module_name.function()。示例:import math 提供 math.sqrt()math.floor()math.piimport 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:"在计算机程序中使用现有子程序(如随机数生成器、子字符串、绝对值)"。
CSTA 3B-AP-16: "Demonstrate code reuse by creating programming solutions using libraries and APIs." AP CSP Big Idea 3 topic 3.14: Libraries. Always check the docs before writing a function — someone may have already written it.CSTA 3B-AP-16:"通过使用库和 API 创建编程解决方案来展示代码复用。" AP CSP 大概念 3 主题 3.14:库。在编写函数之前务必查阅文档——可能已经有人写好了。
WE
Worked Example 7 · Using math and random library functions例题 7 · 使用 math 和 random 库函数

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 文档来查找任何内置函数的签名。

In Python, what must you write before using math.sqrt()?在 Python 中,使用 math.sqrt() 之前必须写什么?
§7 · Q1
use math
include math
import math
require math
In Python, you import a standard library module with 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 模块中的所有其他函数。
Python's keyword for loading a module is import. use and require are keywords in other languages; include is used in C/C++. Only import math works in Python.Python 加载模块的关键字是 importuserequire 是其他语言的关键字;include 用于 C/C++。只有 import math 在 Python 中有效。
Ontario ICS3U expectation A3.1 says students must be able to "use existing subprograms (e.g., random number generator, substring, absolute value)." Which Python call returns the absolute value of -7?安大略 ICS3U 期望 A3.1 要求学生能够"使用现有子程序(如随机数生成器、子字符串、绝对值)"。哪个 Python 调用返回 -7 的绝对值?
§7 · Q2
abs(-7)
math.abs(-7)
absolute(-7)
Math.abs(-7)
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考试策略与常见陷阱

Discipline when writing functions编写函数时的纪律
  • 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 and scope questions (§3–§5)形参与作用域问题(§3–§5)
  • 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).当追踪同时包含全局变量和局部变量的程序时,画两个独立的列或区域:一个表示全局状态,一个表示当前函数的局部状态。分开显示;考官会对正确显示局部变量不影响全局变量(反之亦然)的答案给分。
Modular design questions (§6)模块化设计问题(§6)
  • 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_scorescompute_averageletter_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.对于模块化设计中的每个函数,说明形参(输入数据)和返回值(输出数据)。这表明你理解接口,而不仅仅是名称。
Answer hygiene作答规范
  • Use pseudocode keywords for function definition questions.函数定义题使用伪代码关键字。 AP CSP uses PROCEDURE name(params) { ... } and RETURN(value). The generic pseudocode is FUNCTION name(params): ... RETURN value. In Python it is def 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闪卡

0 / 14 flipped0 / 14 已翻
Function函数(function)
A named, reusable block of code. Defined once with FUNCTION / def; called many times. Supports reuse, abstraction, and decomposition.具名的、可复用的代码块。用 FUNCTION / def 定义一次;多次调用。支持复用、抽象和分解。
Parameter vs Argument形参 vs 实参
Parameter = variable in the definition (placeholder). Argument = actual value at the call site. In def f(n), n is a parameter. In f(7), 7 is an argument.形参(parameter)= 定义中的变量(占位符)。实参(argument)= 调用处的实际值。在 def f(n) 中,n 是形参。在 f(7) 中,7 是实参。
Return value返回值(return value)
The value sent back to the caller by the RETURN / return statement. The caller can store it: x = square(5) stores 25 in x. RETURN also exits the function immediately.由 RETURN / return 语句传回调用方的值。调用方可以存储它:x = square(5) 将 25 存入 x。RETURN 也立即退出函数。
Local variable局部变量(local variable)
Created inside a function. Visible only inside that function. Destroyed when the function returns. Two functions can each have a local called total without conflict.在函数内部创建。只在该函数内可见。函数返回时销毁。两个函数各自可以有名为 total 的局部变量,互不冲突。
Global variable全局变量(global variable)
Created outside all functions. Visible everywhere in the program. Changing it inside one function affects all other code. Prefer local variables; pass data via parameters.在所有函数外创建。在程序的所有地方可见。在一个函数内更改它会影响所有其他代码。优先使用局部变量;通过形参传递数据。
Scope作用域(scope)
Which parts of the code can read/write a variable. Local scope = inside one function. Global scope = everywhere. AB CSE2110 outcome 3.3: "analyze and determine the type of scope required."代码的哪些部分可以读/写一个变量。局部作用域 = 函数内部。全局作用域 = 所有地方。AB CSE2110 结果 3.3:"分析并确定所需的作用域类型"。
Procedure vs Function (AB CSE2110)过程 vs 函数(AB CSE2110)
Procedure = subprogram with no return value (void). Function = subprogram that returns a value. AB CSE2110 outcome 3.2 tests this distinction explicitly.过程(procedure)= 无返回值的子程序(void)。函数(function)= 有返回值的子程序。AB CSE2110 结果 3.2 明确考查这一区别。
Modular design模块化设计(modular design)
Organising a program as a set of functions, each with one clearly-named responsibility. Data flows via parameters and return values. ICS3U B2.3: "apply the principle of modularity."将程序组织为一组函数,每个函数只有一个命名清晰的职责。数据通过形参和返回值流动。ICS3U B2.3:"应用模块化原则"。
Abstraction via functions函数的抽象(abstraction)
A function hides how it works; the caller only needs the interface (name + parameters + return). AP CSP LO AAP-3.B: "Use abstraction to manage complexity in a program."函数隐藏其工作方式;调用方只需了解接口(名称 + 形参 + 返回值)。AP CSP 学习目标 AAP-3.B:"使用抽象管理程序中的复杂性"。
Library库(library)
A collection of pre-written functions. Use with 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:通过库实现代码复用。
Built-in functions内置函数(built-in function)
Available in Python without importing: 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()
Top-down design自顶向下设计(top-down design)
Write the main program first using high-level function calls; then implement each called function. Each step in main becomes a call. Keeps main readable; complexity is in the sub-functions.首先使用高层函数调用编写主程序;然后实现每个被调用的函数。主程序中的每个步骤变成一个调用。主程序保持可读性;复杂性在子函数中。
CSTA 3A-AP-18 (verbatim)CSTA 3A-AP-18(原文)
"Create artifacts by using procedures within a program, combinations of data and procedures, or independent but interrelated programs.""通过在程序中使用过程、数据与过程的组合,或相互关联的独立程序来创建制品。"
ICS3U A3.2 (verbatim)ICS3U A3.2(原文)
"Write subprograms (e.g., functions, procedures) that use parameter passing and appropriate variable scope (e.g., local, global), to perform tasks within programs.""编写使用参数传递和适当变量作用域(如局部、全局)在程序中执行任务的子程序(如函数、过程)。"

Practice Quiz综合测验

What is the return value of FUNCTION triple(n): RETURN n * 3 END FUNCTION when called as triple(4)?FUNCTION triple(n): RETURN n * 3 END FUNCTIONtriple(4) 调用时,返回值是多少?
Q1
4
3
7
12
Argument 4 binds to parameter n. The function returns 4 * 3 = 12.实参 4 绑定到形参 n。函数返回 4 * 3 = 12
n receives the argument value 4. RETURN sends back n * 3 = 4 * 3 = 12.n 接收实参值 4。RETURN 传回 n * 3 = 4 * 3 = 12。
Consider: 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 是多少?
Q2
15
10
5
Depends on the function name取决于函数名称
Without 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。
Without 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 的赋值创建一个局部变量。全局变量不变。这就是为什么在函数内修改全局变量需要显式声明。
A student writes a 60-line program in one block. Their teacher says to refactor it into functions. What is the main benefit?一名学生将一个 60 行程序写在一个代码块中。老师说要将其重构为函数。主要好处是什么?
Q3
Each function can be tested independently, bugs are easier to isolate, and code is reusable每个函数可以独立测试,错误更容易隔离,代码可复用
The program runs faster程序运行更快
The file uses less disk space文件使用更少的磁盘空间
It prevents all runtime errors它防止所有运行时错误
Modular design (functions) makes each sub-problem independently testable and reusable. Bugs are isolated to one function instead of hiding anywhere in 60 lines. ICS3U B2.3 and AB CSE2110 both cite this as the primary benefit.模块化设计(函数)使每个子问题可以独立测试和复用。错误被隔离到一个函数中,而不是隐藏在 60 行的任何地方。ICS3U B2.3 和 AB CSE2110 都将此列为主要好处。
Refactoring into functions improves maintainability and testability, not runtime speed or file size. The key benefit is modular testability and reuse.将代码重构为函数提高了可维护性和可测试性,而不是运行速度或文件大小。关键好处是模块化可测试性和复用。
What does import math allow you to do?import math 允许你做什么?
Q4
Define a new module called math定义一个名为 math 的新模块
Use math inside a loop only只在循环内使用 math
Call pre-built functions like math.sqrt(), math.floor(), math.pi调用预建函数如 math.sqrt()math.floor()math.pi
Replace the built-in arithmetic operators替换内置算术运算符
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 加载现有模块;不定义新模块或限制使用。导入后,模块的函数在文件的任何地方都可用。
In the function FUNCTION greet(name): OUTPUT "Hi " + name, what kind of subprogram is this? 🇨🇦 AB CSE2110在函数 FUNCTION greet(name): OUTPUT "Hi " + name 中,这是哪种子程序?🇨🇦 AB CSE2110
Q5
A value-returning function有返回值函数(value-returning function)
A procedure / void function过程 / 无返回值函数(procedure / void function)
A library function库函数(library function)
A parameter形参(parameter)
The function performs an action (output) but has no RETURN statement, so it is a procedure or void function. AB CSE2110 outcome 3.2: "functions (subprograms that return a value) and procedures (subprograms that do not return a value)."该函数执行一个操作(输出)但没有 RETURN 语句,所以它是一个过程或无返回值函数。AB CSE2110 结果 3.2:"函数(有返回值的子程序)和过程(无返回值的子程序)"。
No RETURN = procedure (void). A value-returning function must have a RETURN statement that sends a value back to the caller.没有 RETURN = 过程(void)。有返回值函数必须有将值传回调用方的 RETURN 语句。
CSTA standard 3A-AP-18 (verbatim) says: "Create artifacts by using __________ within a program." 🇺🇸 CSTACSTA 标准 3A-AP-18(原文):"通过在程序中使用 __________ 来创建制品。" 🇺🇸 CSTA
Q6
procedures过程(procedures)
global variables全局变量(global variables)
flowcharts流程图(flowcharts)
pseudocode伪代码(pseudocode)
CSTA 3A-AP-18 (verbatim): "Create artifacts by using procedures within a program, combinations of data and procedures, or independent but interrelated programs."CSTA 3A-AP-18(原文):"通过在程序中使用过程、数据与过程的组合,或相互关联的独立程序来创建制品。"
The standard specifically names "procedures" (subprograms). 3A-AP-18 is the procedural-programming companion to 3A-AP-17 (decomposition).该标准具体指名"过程"(子程序)。3A-AP-18 是 3A-AP-17(分解)的过程化编程配套标准。
Ontario ICS3U expectation A3.2 requires students to write subprograms that use what two features? 🇨🇦 ON ICS3U安大略 ICS3U 期望 A3.2 要求学生编写使用哪两个特性的子程序?🇨🇦 ON ICS3U
Q7
flowcharts and pseudocode流程图和伪代码
loops and conditionals循环和条件语句
parameter passing and appropriate variable scope参数传递和适当的变量作用域
libraries and APIs库和 API
ICS3U A3.2 (verbatim): "write subprograms (e.g., functions, procedures) that use parameter passing and appropriate variable scope (e.g., local, global), to perform tasks within programs."ICS3U A3.2(原文):"编写使用参数传递适当变量作用域(如局部、全局)在程序中执行任务的子程序(如函数、过程)。"
A3.2 specifically assesses parameter passing and variable scope. Sections 3, 4, and 5 of this guide cover exactly those two features.A3.2 专门评估参数传递和变量作用域。本指南的第 3、4、5 节正好涵盖这两个特性。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

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 CSA Unit 1 · Using Objects and Methods (Java methods are functions; calling a method is exactly what you practised here with pseudocode calls)AP CSA Unit 1 · 使用对象和方法(Java 方法就是函数;调用方法与你在这里用伪代码调用所练习的完全相同)

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 课程之前掌握本单元,可以消除入门编程中最常见的困惑来源。