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 演示。
Why Functions? Reuse and Abstraction为什么要用函数?复用与抽象
- State three reasons to use a function: reuse, abstraction and decomposition.
- Rewrite repeated code as one function and call it from each place.
- Explain why a caller needs only a function's name, inputs and output, not its body.
- Count how many edits a rule change needs with and without a function.
- 说出使用函数的三个理由:复用、抽象和分解。
- 把重复的代码改写为一个函数,并在每个位置调用它。
- 解释为什么调用方只需要知道函数的名称、输入和输出,而不需要知道函数体。
- 数出有函数和没有函数时,规则改变各需要多少处修改。
- 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 Computational Thinking Practice 3.B: "Use abstraction to manage complexity in a program.", 调用方只需知道函数做什么(名称、输入、输出),而不需要知道如何做。这隐藏了复杂性,让你在更高层次上思考。AP CSP 计算思维实践 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) 时,你不需要知道内部算法,只需信任接口。构建自己的函数,就能给调用者带来同样的好处。
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:"应用模块化原则设计可复用代码。"
Worked Example 2: Changing a rule in one place例题 2:只在一处修改规则
Problem: a shop adds 13 percent tax at the till, on the receipt and on the web page. Show the code with the formula copied three times, then as one function, and show what has to change when the rate becomes 15 percent. Use the prices 20.00, 8.00 and 50.00.问题:一家商店在收银台、收据和网页上都要加 13% 的税。展示把公式复制三次的代码,再展示改成一个函数的代码,并说明税率变为 15% 时需要修改什么。使用价格 20.00、8.00 和 50.00。
Pseudocode.伪代码。
-- Version A: the formula is copied into each place
SET till TO ROUND(20.00 * 1.13, 2)
SET receipt TO ROUND(8.00 * 1.13, 2)
SET web TO ROUND(50.00 * 1.13, 2)
-- Version B: the formula lives in one function
FUNCTION with_tax(price):
RETURN ROUND(price * 1.13, 2)
END FUNCTION
SET till TO with_tax(20.00)
SET receipt TO with_tax(8.00)
SET web TO with_tax(50.00)Version A repeats the tax formula three times. When the rate changes you must find and edit every copy, and missing one gives two different prices for the same item. In version B the formula appears once; each caller only writes the function name and the price.版本 A 把税率公式重复了三次。税率改变时必须找到并修改每一处副本,漏掉一处就会让同一商品出现两个不同价格。在版本 B 中公式只出现一次;每个调用方只需写出函数名和价格。
Python rendering.Python 实现。
def with_tax(price):
return round(price * 1.13, 2)
print(with_tax(20.00)) # 22.6
print(with_tax(8.00)) # 9.04
print(with_tax(50.00)) # 56.5Each result is the price times 1.13, rounded to 2 decimal places: 20.00 × 1.13 = 22.6, 8.00 × 1.13 = 9.04, 50.00 × 1.13 = 56.5. Python prints 22.6, not 22.60, because a float does not keep trailing zeros.每个结果都是价格乘以 1.13 后保留 2 位小数:20.00 × 1.13 = 22.6,8.00 × 1.13 = 9.04,50.00 × 1.13 = 56.5。Python 输出 22.6 而不是 22.60,因为浮点数不保留末尾的零。
The rate changes to 15 percent.税率改为 15%。
def with_tax(price):
return round(price * 1.15, 2) # the only line that changed
print(with_tax(20.00)) # 23.0
print(with_tax(8.00)) # 9.2
print(with_tax(50.00)) # 57.5Only one line was edited, and every caller is correct without being touched. The callers never needed to know the formula, only the name with_tax and what it returns: that is abstraction. Why this works: a function gives one rule one home, so a change to the rule is one edit.只修改了一行,所有调用方都无需改动就得到正确结果。调用方从来不需要知道公式,只需要知道名称 with_tax 和它返回什么:这就是抽象。原因:函数让一条规则只有一个存放位置,所以规则改变只需一次修改。
When a question says explain why a function helps, tie the reason to the code you are given: “the tax formula is written three times, so a change needs three edits; a function needs one.” A bare “it is neater” is an incomplete answer. Do not write that functions make a program run faster: a function call does not make a program faster.
当题目要求解释函数的好处时,要把理由和所给代码联系起来:“税率公式写了三次,所以改动需要修改三处;使用函数只需修改一处。”只写“更整洁”是不完整的答案。不要写函数使程序运行更快:调用函数并不会让程序更快。
State two benefits of replacing five copies of the same 10-line calculation with one function.说出把同一段 10 行计算的五个副本换成一个函数的两个好处。
Any two of: a change or bug fix is made in one place instead of five; the program is shorter and easier to read; the function can be tested on its own; it can be reused wherever the calculation is needed.
以下任意两点:修改或修复错误只需在一处而不是五处;程序更短、更易读;函数可以单独测试;任何需要该计算的地方都可以复用它。
A program computes price * 0.13 in 4 separate places. How many lines must be edited to change the rate to 0.15 (a) as written, and (b) if the formula is moved into one function?一个程序在 4 个不同位置计算 price * 0.13。要把税率改为 0.15,需要修改多少行:(a) 按现有写法,(b) 把公式移入一个函数后?
(a) 4 lines, one per copy. (b) 1 line, the one inside the function. The four callers are unchanged.
(a) 4 行,每个副本一行。(b) 1 行,即函数内部那一行。四个调用方不变。
Given def with_tax(price): return round(price * 1.13, 2), what does with_tax(50.00) return, and what does a caller need to know to use it?已知 def with_tax(price): return round(price * 1.13, 2),with_tax(50.00) 返回什么?调用方需要知道什么才能使用它?
It returns 56.5, because 50.00 × 1.13 = 56.5. The caller needs only the interface: the name with_tax, that it takes one price, and that it returns the price with tax. It does not need to see the formula.
返回 56.5,因为 50.00 × 1.13 = 56.5。调用方只需要知道接口:名称 with_tax、它接受一个价格、并返回含税价格。不需要看到公式。
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定义与调用函数
- Distinguish a function definition from a function call.
- State that a definition stores the body without running it.
- Trace the order in which lines run when one function calls another.
- Explain why calling a function before its
defline has run gives a NameError.
- 区分函数定义与函数调用。
- 说明定义只存放函数体而不运行它。
- 追踪一个函数调用另一个函数时各行的运行顺序。
- 解释为什么在
def行运行之前调用函数会产生 NameError。
- 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)。程序跳入函数体,执行后返回调用处。
Worked Example 3: Defining and calling a greeting function例题 3:定义和调用问候函数
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。
Worked Example 4: Order of definition and call例题 4:定义与调用的顺序
Problem: predict the output of the program below, tracing which line runs when. Then explain what goes wrong if the call announce() is moved above its definition.问题:预测下面程序的输出,并追踪每一行何时运行。然后解释如果把调用 announce() 移到它的定义上方会出什么问题。
Version A: predict the output.版本 A:预测输出。
def announce():
print("start")
greet("Cy")
print("end")
def greet(name):
print("Hi " + name)
announce()Trace, one step at a time.逐步追踪。
def announce()runs: Python stores the function under the nameannounce. Nothing is printed.def announce()执行:Python 把函数存放在名称announce下。不输出任何内容。def greet(name)runs: stored the same way. Nothing is printed.def greet(name)执行:以同样方式存放。不输出任何内容。announce()is called. Control jumps into its body and printsstart.调用announce()。控制权跳入其函数体并输出start。- Inside it,
greet("Cy")is called, sonamebecomes"Cy"andHi Cyis printed.greetfinishes and control returns to the line after the call.在其中调用greet("Cy"),于是name变为"Cy",输出Hi Cy。greet结束,控制权回到调用之后的那一行。 announceprintsendand finishes.announce输出end并结束。
Output, in order: start, Hi Cy, end. Notice that greet is defined after announce in the file, yet the program works: announce only runs when it is called, and by then both definitions have executed.输出顺序:start、Hi Cy、end。注意 greet 在文件中定义在 announce 之后,程序仍然能运行:announce 只在被调用时才运行,而那时两个定义都已执行。
Version B: call before definition.版本 B:先调用后定义。
announce() # called before the def line has run
def announce():
print("start")This stops with NameError: name 'announce' is not defined. When the first line runs, Python has not yet executed the def line, so the name does not exist. Fix: move the call below the definition. Why this works: def is a statement that creates the name when it executes; it is not a declaration read in advance.这会以 NameError: name 'announce' is not defined 终止。第一行执行时,Python 还没有执行 def 那一行,所以这个名称不存在。修复:把调用移到定义之下。原因:def 是一条在执行时才创建名称的语句,而不是提前读取的声明。
In a trace question, write the output in the order the print calls run, not the order the lines appear on the page. Definitions print nothing. Use the words define and call precisely: “the function is defined on line 1 and called on line 5”.
在追踪题中,按 print 调用运行的顺序写出输出,而不是按代码在页面上出现的顺序。定义本身不输出任何内容。要准确使用定义和调用这两个词:“函数在第 1 行定义,在第 5 行调用”。
def show():
print("A")
print("B")
show()
print("C")
What does the program above print, in order?上面的程序按顺序输出什么?
B, then A, then C. The def prints nothing; print("B") runs first; show() then prints A; finally print("C") runs.
依次输出 B、A、C。def 不输出任何内容;先运行 print("B");然后 show() 输出 A;最后运行 print("C")。
def f():
print("X")
def g():
f()
f()
g()
How many times does this program print X? Explain.这个程序输出 X 多少次?请解释。
Twice. Only g() is called from the main program; it calls f() two times, and each call prints one X.
两次。主程序只调用了 g();它调用 f() 两次,每次调用输出一个 X。
A student writes hello() on line 1 and def hello(): print("hi") on line 3. State the error and one fix.一名学生在第 1 行写 hello(),在第 3 行写 def hello(): print("hi")。指出错误并给出一种修复方法。
It is a NameError: the name hello does not exist yet when line 1 runs, because the def on line 3 has not executed. Fix: move the call so it comes after the definition.
这是 NameError:第 1 行运行时名称 hello 还不存在,因为第 3 行的 def 尚未执行。修复:把调用移到定义之后。
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形参与实参
- Identify the parameters in a definition and the arguments in a call.
- Call a function with positional and with keyword arguments.
- Give a parameter a default value and predict the result when the argument is left out.
- Explain the mutable default argument trap and fix it with
None.
- 识别定义中的形参和调用中的实参。
- 用位置实参和关键字实参调用函数。
- 为形参设置默认值,并预测省略实参时的结果。
- 解释可变默认实参的陷阱,并用
None修复它。
- 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 涵盖"单向和双向参数传递"。
Worked Example 5: A function with two parameters例题 5:带两个形参的函数
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 不会影响函数外的任何变量,这就是单向参数传递的实际效果。
Worked Example 6: Default values, keyword arguments and the mutable default trap例题 6:默认值、关键字实参与可变默认值陷阱
Problem: write make_label(name, greeting, punct) so that the greeting and punctuation can be left out, and call it four ways. Then show why a list used as a default argument misbehaves and how to fix it.问题:编写 make_label(name, greeting, punct),使问候语和标点可以省略,并用四种方式调用它。然后说明为什么用列表作为默认实参会出错以及如何修复。
Default and keyword arguments.默认实参与关键字实参。
def make_label(name, greeting="Hello", punct="!"):
return greeting + ", " + name + punct
print(make_label("Ana")) # Hello, Ana!
print(make_label("Ana", punct="?")) # Hello, Ana?
print(make_label(greeting="Hi", name="Ben")) # Hi, Ben!
print(make_label("Cy", "Hey")) # Hey, Cy!name has no default, so every call must supply it. greeting and punct have defaults ("Hello" and "!"), used when the caller leaves them out. The second call uses the keyword punct="?" to change only that one. The third call names both arguments, so their order does not matter. The fourth call is positional: "Cy" goes to name and "Hey" to greeting. A call that mixes the two styles must put positional arguments first.name 没有默认值,所以每次调用都必须提供它。greeting 和 punct 有默认值("Hello" 和 "!"),调用方省略它们时使用默认值。第二次调用用关键字 punct="?" 只改变这一项。第三次调用写出了两个实参的名称,所以顺序无关紧要。第四次调用是位置实参:"Cy" 给 name,"Hey" 给 greeting。混用两种写法时,位置实参必须在前。
Common error: a mutable default argument.常见错误:可变的默认实参。
def add_item(item, bag=[]): # the default list is created once
bag.append(item)
return bag
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] (surprise: 'a' is still there)A default value is evaluated once, when the def line runs, not on every call. The empty list [] is therefore created one time and shared by every call that omits bag, so the second call finds 'a' already inside. The first line printed ['a'] only because the list was empty at that point.默认值只在 def 行运行时计算一次,而不是每次调用都计算。因此空列表 [] 只创建一次,被所有省略 bag 的调用共用,所以第二次调用时 'a' 已经在里面了。第一行输出 ['a'] 只是因为那时列表是空的。
The fix: default to None.修复方法:默认值设为 None。
def add_item(item, bag=None):
if bag is None:
bag = [] # a new list on every call
bag.append(item)
return bag
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']Now each call that omits bag builds its own new list, so the calls no longer affect each other. Why this works: None is immutable and safe to share, and the test bag is None runs on every call, so the new list is made fresh each time. Numbers, strings and None are safe defaults; lists, dictionaries and sets are not.现在每个省略 bag 的调用都会新建自己的列表,调用之间不再互相影响。原因:None 不可变,共用是安全的,而 bag is None 的判断在每次调用时都会运行,所以每次都会新建列表。数字、字符串和 None 是安全的默认值;列表、字典和集合则不是。
Use the words parameter (in the definition) and argument (in the call) precisely. In a call, positional arguments come before keyword arguments: f(greeting="Hi", "Ben") is a SyntaxError. If a question gives a list as a default value and asks for the output of two calls, expect the first call's items to still be in the list on the second call.
要准确使用形参(在定义中)和实参(在调用中)这两个词。调用时位置实参必须在关键字实参之前:f(greeting="Hi", "Ben") 是 SyntaxError。如果题目给出以列表作为默认值,并要求写出两次调用的输出,要预料到第二次调用时第一次调用的元素仍在列表中。
def area(w, h=1):
return w * h
print(area(5))
print(area(5, 3))
print(area(h=4, w=2))
Which parameter has a default value? What does each of the three calls print?哪个形参有默认值?三次调用各输出什么?
h has the default 1. The calls print 5 (5 × 1), 15 (5 × 3) and 8 (keywords w=2, h=4, so 2 × 4).
h 的默认值是 1。三次调用分别输出 5(5 × 1)、15(5 × 3)和 8(关键字 w=2、h=4,所以 2 × 4)。
def collect(x, acc=[]):
acc.append(x)
return acc
print(collect(1))
print(collect(2))
What do the two calls print, and what is wrong with the function? Give the fix.两次调用各输出什么?这个函数有什么问题?给出修复方法。
They print [1] and then [1, 2]. The default list is created once and shared, so the second call still contains the 1. Fix: use acc=None and, inside the function, if acc is None: acc = []. The second call then prints [2].
先输出 [1],再输出 [1, 2]。默认列表只创建一次并被共用,所以第二次调用时里面仍有 1。修复:使用 acc=None,并在函数内写 if acc is None: acc = []。这样第二次调用输出 [2]。
def power(base, exponent):
result = 1
for i in range(exponent):
result = result * base
return result
For the function above, what does power(exponent=3, base=2) return? What happens with power(2)?对于上面的函数,power(exponent=3, base=2) 返回什么?power(2) 会怎样?
The first call returns 8 (2 multiplied 3 times; keyword order does not matter). power(2) raises a TypeError saying exponent is a missing required positional argument, because exponent has no default.
第一次调用返回 8(2 相乘 3 次;关键字的顺序无关紧要)。power(2) 会引发 TypeError,提示缺少必需的位置实参 exponent,因为 exponent 没有默认值。
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返回值
- Distinguish a function that returns a value from a procedure that does not.
- Explain the difference between
returnandprint. - State that a function with no executed
returngivesNone. - Use an early
returninside a loop or anifand predict which values are never examined.
- 区分有返回值的函数与没有返回值的过程。
- 解释
return与print的区别。 - 说明没有执行
return的函数得到None。 - 在循环或
if中使用提前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 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)。如果调用有返回值的函数时不捕获结果,值将被丢弃。
Worked Example 7: A grade classifier function with early return例题 7:带提前返回的成绩分类函数
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。
Worked Example 8: Return versus print, and the value None例题 8:return 与 print,以及值 None
Problem: two functions both “double” a number, one with print and one with return. Predict what happens when each result is stored and used in arithmetic. Then explain what a search function returns when it finds nothing.问题:两个函数都对数字“翻倍”,一个用 print,一个用 return。预测把各自的结果存储并用于运算时会发生什么。然后解释查找函数在什么都没找到时返回什么。
print versus return.print 与 return。
def double_print(n):
print(n * 2) # shows a value, returns nothing
def double_ret(n):
return n * 2 # sends a value back
x = double_print(4) # prints 8
print(x) # None
y = double_ret(4) # prints nothing
print(y + 1) # 9
# print(x + 1) would stop with:
# TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'double_print(4) displays 8 on the screen, but the function has no return, so the call itself produces the value None. Storing it in x and printing x shows None, and adding 1 to it is a TypeError. double_ret(4) prints nothing by itself; it hands 8 back, so y + 1 is 9 and the caller can keep using the result.double_print(4) 在屏幕上显示 8,但函数没有 return,所以这次调用本身产生的值是 None。把它存入 x 再输出 x 显示 None,对它加 1 会产生 TypeError。double_ret(4) 自己不输出任何内容;它把 8 交还给调用方,所以 y + 1 是 9,调用方可以继续使用这个结果。
A function that sometimes forgets to return.有时忘记返回值的函数。
def first_negative(nums):
for v in nums:
if v < 0:
return v # leaves the function at once
# no return here: falls off the end
print(first_negative([3, 5, -2, -7])) # -2
print(first_negative([1, 2])) # NoneThe first call reaches return v when v is -2 and leaves immediately, so -7 is never examined. The second list has no negative number, so the loop ends and the function reaches its last line without a return; Python then returns None. If a caller expects a number, decide what to return in the not-found case and write it explicitly, for example return None on purpose or a value such as 0. Why this works: every Python function returns something, and None is what you get when no return runs.第一次调用在 v 为 -2 时执行 return v 并立即退出,所以 -7 从未被检查。第二个列表没有负数,循环结束,函数到达最后一行时没有执行 return;Python 随后返回 None。如果调用方期望得到数字,就要决定未找到时返回什么并明确写出,例如有意写 return None,或返回 0 之类的值。原因:每个 Python 函数都会返回某个值,没有任何 return 运行时得到的就是 None。
Return and display are different command words. If a question says “return the average”, the function must end with return; a print alone is not a return and leaves the caller holding None. If a question says “write a procedure to display the result”, do not add a return statement. Always say what the function gives back when no branch matches.
返回(return)和显示(display)是不同的指令词。如果题目说“返回平均值”,函数必须以 return 结尾;只用 print 不是返回,调用方得到的是 None。如果题目说“编写一个过程来显示结果”,就不要添加 return 语句。始终说明没有任何分支匹配时函数返回什么。
def f(n):
n * 2
print(f(3))
What does the program print, and why is it not 6?程序输出什么?为什么不是 6?
It prints None. The line n * 2 computes 6 and throws it away; there is no return. Fix: return n * 2.
输出 None。n * 2 这一行算出 6 后就丢弃了;函数中没有 return。修复:写成 return n * 2。
def sign(n):
if n > 0:
return "pos"
if n < 0:
return "neg"
print(sign(5))
print(sign(0))
What do the two calls print? Add one line so that sign(0) gives "zero".两次调用各输出什么?添加一行使 sign(0) 得到 "zero"。
pos and then None: for 0 neither if is true, so no return runs. Add return "zero" as the last line of the function, at the same indentation as the if lines.
输出 pos,然后是 None:对于 0,两个 if 都不成立,所以没有 return 运行。在函数最后一行添加 return "zero",缩进与 if 行相同。
Write is_even(n) that returns True when n is even and False otherwise. What does is_even(7) return?编写 is_even(n),当 n 为偶数时返回 True,否则返回 False。is_even(7) 返回什么?
def is_even(n): return n % 2 == 0. For 7, 7 % 2 is 1, and 1 == 0 is false, so it returns False.
def is_even(n): return n % 2 == 0。对于 7,7 % 2 是 1,1 == 0 为假,所以返回 False。
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变量作用域:局部变量与全局变量
- Classify each variable in a program as local or global.
- Predict the output when a function assigns to a name that is also global.
- Explain why assigning to a global name inside a function without
globalcan causeUnboundLocalError. - Repair such a function with
global, or better with a parameter and a return value.
- 把程序中的每个变量归类为局部变量或全局变量。
- 预测函数对同名全局变量赋值时的输出。
- 解释为什么在函数内不使用
global而对全局名称赋值可能导致UnboundLocalError。 - 用
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 明确要求"适当的变量作用域(如局部、全局)"。
Worked Example 9: Tracing local vs global scope例题 9:追踪局部作用域与全局作用域
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 作为形参传入,并返回结果。
Worked Example 10: UnboundLocalError and shadowing例题 10:UnboundLocalError 与变量遮蔽
Problem: a program keeps a global count and a function bump that adds 1 to it with count = count + 1. Explain why calling bump() fails, show what happens when a function assigns to a name that is also global, and give two fixes.问题:程序有一个全局变量 count,函数 bump 用 count = count + 1 给它加 1。解释为什么调用 bump() 会失败,展示函数对同名全局变量赋值时会发生什么,并给出两种修复方法。
The failing program.出错的程序。
count = 0
def bump():
count = count + 1 # assigns to count, so count is local here
return count
bump()
# UnboundLocalError: cannot access local variable 'count' where it is
# not associated with a valuePython decides, before running a function, which names are local: any name that is assigned inside the function body is local for the whole body. In bump, count = count + 1 assigns to count, so count is local. The right-hand side then reads a local count that has no value yet, and Python raises UnboundLocalError. It does not fall back to the global count = 0. The exact wording of the message differs between Python versions (older versions say “local variable 'count' referenced before assignment”), but the error name is the same.Python 在运行函数之前就会确定哪些名称是局部的:在函数体内被赋值的名称,在整个函数体中都是局部的。在 bump 中,count = count + 1 对 count 赋值,所以 count 是局部变量。右边随后读取一个尚无值的局部 count,Python 因此引发 UnboundLocalError。它不会退回去使用全局的 count = 0。错误信息的具体措辞随 Python 版本而异(旧版本写作“local variable 'count' referenced before assignment”),但错误名称相同。
A related trap: shadowing.相关陷阱:变量遮蔽。
total = 10
def shadow():
total = 99 # a new local variable, not the global
return total
print(shadow()) # 99
print(total) # 10 (the global was never touched)Here the function only assigns total, never reads it first, so there is no error: total = 99 creates a new local that hides the global inside shadow. After the call the global is still 10.这里函数只对 total 赋值,没有先读取它,所以没有错误:total = 99 创建了一个新的局部变量,在 shadow 内部遮蔽了全局变量。调用之后全局变量仍是 10。
Fix 1 (preferred): parameter in, return out.修复 1(推荐):形参传入,返回值传出。
count = 0
def bump(c):
return c + 1 # works only with its parameter
count = bump(count) # the caller stores the result
print(count) # 1Fix 2: declare the global.修复 2:声明全局变量。
count = 0
def bump():
global count # tell Python: count is the global one
count = count + 1
bump()
bump()
print(count) # 2Both fixes work. Fix 1 keeps the function independent of hidden state: bump(5) always gives 6. Fix 2 changes shared state, so the result of bump() depends on how many times it ran before, which makes bugs harder to find. Why this works: global count tells Python that assignments to count inside this function refer to the module-level variable, so no local is created.两种修复都有效。修复 1 让函数不依赖隐藏状态:bump(5) 总是得到 6。修复 2 会改变共享状态,所以 bump() 的结果取决于之前运行了多少次,这使错误更难发现。原因:global count 告诉 Python,此函数内对 count 的赋值指向模块级变量,因此不会创建局部变量。
In a scope trace, keep two columns: one for the global variables and one for the current function's locals, and update them line by line. A name that is assigned anywhere in a function is local to that whole function, even on lines before the assignment. Reading a global without assigning to it needs no global keyword.
在作用域追踪题中,保留两列:一列记录全局变量,一列记录当前函数的局部变量,并逐行更新。在函数内任何位置被赋值的名称,在整个函数中都是局部的,即使在赋值之前的行也是如此。只读取而不赋值的全局变量不需要 global 关键字。
x = 5
def f():
x = 20
return x
print(f(), x)
What does the program print? Name the local and the global variable.程序输出什么?指出局部变量和全局变量。
It prints 20 5. Inside f, x = 20 creates a local x; the global x stays 5.
输出 20 5。在 f 内,x = 20 创建了局部变量 x;全局变量 x 仍是 5。
A program has n = 1 at the top and def up(): n = n + 1. Why does calling up() raise UnboundLocalError, and what are two fixes?程序开头有 n = 1,并有 def up(): n = n + 1。为什么调用 up() 会引发 UnboundLocalError?有哪两种修复方法?
Assigning to n makes n local to up, so the right-hand n is read before it has a value. Fixes: add global n as the first line of up; or, better, write def up(n): return n + 1 and call n = up(n).
对 n 赋值使 n 成为 up 的局部变量,所以右边的 n 在有值之前就被读取了。修复:在 up 的第一行添加 global n;或者更好的做法是写 def up(n): return n + 1 并调用 n = up(n)。
n = 1
def show():
print(n)
show()
n = 2
show()
What does this program print? Does show need the global keyword?这个程序输出什么?show 需要 global 关键字吗?
It prints 1 and then 2. show only reads n, and a read finds the global, so no global keyword is needed; the second call sees the updated value 2.
输出 1 然后是 2。show 只读取 n,读取时会找到全局变量,所以不需要 global 关键字;第二次调用看到更新后的值 2。
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") addresses precisely 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模块化设计:将程序分解为函数
- Decompose a task into functions, naming each by a verb and noun and stating its parameters and return value.
- Draw the data flow between functions: what goes in and what comes back.
- Trace a recursive call on a call stack and read the values returned.
- Identify the base case of a recursive function and explain what happens without one.
- 把任务分解为函数,用动词加名词命名每个函数,并说明其形参和返回值。
- 画出函数之间的数据流:什么传入,什么传回。
- 在调用栈上追踪递归调用,并读出返回的值。
- 识别递归函数的基例,并解释没有基例会发生什么。
- 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])连接到其余部分之前单独测试它。隔离错误变得轻而易举。
Worked Example 11: A grade-book program in four functions例题 11:用四个函数实现成绩册程序
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)
Worked Example 12: Recursion and the call stack例题 12:递归与调用栈
Problem: write a function fact(n) that returns n factorial (n × (n − 1) × ... × 1) by calling itself. Trace fact(4) on the call stack and explain what the base case is for.问题:编写函数 fact(n),通过调用自身返回 n 的阶乘(n × (n − 1) × ... × 1)。在调用栈上追踪 fact(4),并解释基例的作用。
Python rendering.Python 实现。
def fact(n):
if n == 1: # base case: stops the recursion
return 1
return n * fact(n - 1) # recursive case: a smaller copy of the problem
print(fact(4)) # 24Trace the call stack (see Figure 1).追踪调用栈(见图 1)。
fact(4)is called withn = 4. It is not the base case, so it must compute4 * fact(3); it waits forfact(3).调用fact(4),n = 4。它不是基例,所以必须计算4 * fact(3);它等待fact(3)。fact(3)waits forfact(2), andfact(2)waits forfact(1). Each call has its ownn, held in its own frame on the stack.fact(3)等待fact(2),fact(2)等待fact(1)。每次调用都有自己的n,保存在栈上自己的帧中。fact(1)is the base case and returns1without calling anything. Its frame is removed.fact(1)是基例,不再调用任何函数,直接返回1。它的帧被移除。- The waiting frames finish from the top down:
fact(2)returns2 * 1 = 2,fact(3)returns3 * 2 = 6,fact(4)returns4 * 6 = 24.等待中的帧从上到下依次完成:fact(2)返回2 * 1 = 2,fact(3)返回3 * 2 = 6,fact(4)返回4 * 6 = 24。
Four calls were made, so four frames were on the stack at the deepest point. The answer 24 equals 4 × 3 × 2 × 1.共进行了四次调用,所以在最深处栈上有四个帧。答案 24 等于 4 × 3 × 2 × 1。
Common error: forgetting the base case.常见错误:忘记基例。
def fact_bad(n):
return n * fact_bad(n - 1) # no base case
fact_bad(3)
# RecursionError: maximum recursion depth exceededWithout the if n == 1 test, nothing ever stops the calls, the stack keeps growing, and Python stops the program with a RecursionError. A correct recursive function needs a base case that returns without recursing, and each recursive call must move closer to it (here n - 1 moves toward 1). Why this works: each frame remembers its own n and the pending multiplication, so the answers can be combined on the way back. This is also decomposition: fact(4) is solved by trusting a smaller call, fact(3).如果没有 if n == 1 这个判断,就没有任何东西能停止调用,栈不断增长,Python 会以 RecursionError 终止程序。正确的递归函数需要有一个不再递归就能返回的基例,并且每次递归调用都必须更接近基例(这里 n - 1 朝 1 靠近)。原因:每个帧都记住自己的 n 和待完成的乘法,所以在返回途中可以把各个答案组合起来。这也是分解:fact(4) 通过信任一个更小的调用 fact(3) 来解决。
print(fact(4)). Each call pushes a frame with its own n; the frame with n = 1 is the base case and returns 1, then each frame below returns n times the value that came back: 2, 6, 24. The returned values are printed beside the frames.图 1. print(fact(4)) 的调用栈。每次调用压入一个带有自己 n 的帧;n = 1 的帧是基例,返回 1,然后下面每个帧返回 n 乘以传回的值:2、6、24。返回值标在各帧旁边。For a decomposition question, list each function with its parameters and what it returns, for example compute_average(scores) returns a number. For a recursion trace, name the base case first, then show each call and each return value in order. A recursive function with no base case is an incomplete answer because it never ends.
对于分解题,列出每个函数及其形参和返回值,例如 compute_average(scores) 返回一个数。对于递归追踪题,先指出基例,然后按顺序给出每次调用和每个返回值。没有基例的递归函数是不完整的答案,因为它永远不会结束。
A program reads a temperature in degrees Celsius, then prints it in Fahrenheit and warns if it is above 30. Propose three functions with their parameters and return values.一个程序读取摄氏温度,然后输出对应的华氏温度,并在温度高于 30 时发出警告。提出三个函数,并说明它们的形参和返回值。
One possible answer: to_fahrenheit(c) returns c * 9 / 5 + 32; is_hot(c) returns True when c > 30; display_report(f, hot) prints the result and returns nothing. The main program calls them in that order, passing each result to the next.
一种可能的答案:to_fahrenheit(c) 返回 c * 9 / 5 + 32;is_hot(c) 在 c > 30 时返回 True;display_report(f, hot) 输出结果,不返回值。主程序按此顺序调用它们,并把每个结果传给下一个。
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(3))
What does the program print? How many calls to total are made, counting the first?程序输出什么?包括第一次在内,一共调用了多少次 total?
It prints 6. The calls are total(3), total(2), total(1) and total(0), which is the base case: 4 calls. The returns are 0, then 1 + 0 = 1, then 2 + 1 = 3, then 3 + 3 = 6.
输出 6。调用依次为 total(3)、total(2)、total(1) 和 total(0)(基例):共 4 次调用。返回值依次为 0,然后 1 + 0 = 1,然后 2 + 1 = 3,然后 3 + 3 = 6。
Using fact from the worked example, how many frames are on the stack at the deepest point of fact(5), and what does it return?使用例题中的 fact,fact(5) 在最深处栈上有多少个帧?它返回什么?
Five frames from fact(5) down to fact(1), plus the main program below them. It returns 5 × 24 = 120, because fact(4) returns 24.
从 fact(5) 到 fact(1) 共五个帧,其下还有主程序。它返回 5 × 24 = 120,因为 fact(4) 返回 24。
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内置函数与库
- Use the built-in functions
len,max,min,sum,absandroundwithout an import. - Import a module and call
math.sqrt,math.floorandmath.ceilwith the module prefix. - Explain why
round(2.5)is 2 and howfloorandintdiffer for negatives. - Read a library function's signature and description to decide how to call it.
- 不用导入就能使用内置函数
len、max、min、sum、abs和round。 - 导入模块,并带模块前缀调用
math.sqrt、math.floor和math.ceil。 - 解释为什么
round(2.5)是 2,以及floor和int对负数有何不同。 - 阅读库函数的签名和说明,以决定如何调用它。
- 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:"在计算机程序中使用现有子程序(如随机数生成器、子字符串、绝对值)"。
Worked Example 13: Using math and random library functions例题 13:使用 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 文档来查找任何内置函数的签名。
Worked Example 14: Built-in functions, the math module and rounding例题 14:内置函数、math 模块与取整
Problem: given the scores 72, 85, 91, 68 and 79, find the highest, lowest, total and mean using built-in functions. Then find how many pages 47 items need at 10 per page, and show how round, math.floor and int treat halves and negative numbers.问题:给定分数 72、85、91、68 和 79,用内置函数求最高分、最低分、总分和平均分。然后求每页 10 项时 47 项需要多少页,并展示 round、math.floor 和 int 如何处理一半和负数。
Python rendering.Python 实现。
import math
scores = [72, 85, 91, 68, 79]
print(max(scores), min(scores)) # 91 68
print(sum(scores), len(scores)) # 395 5
print(sum(scores) / len(scores)) # 79.0
pages = math.ceil(47 / 10) # 47 items, 10 per page
print(pages) # 5
print(round(2.5), round(3.5)) # 2 4
print(math.floor(-4.7), int(-4.7)) # -5 -4max, min, sum and len are built-in functions, so no import is needed. The scores add to 72 + 85 + 91 + 68 + 79 = 395, and 395 / 5 = 79.0; the / operator always gives a float, which is why the output is 79.0 and not 79.max、min、sum 和 len 是内置函数,所以不需要 import。分数之和为 72 + 85 + 91 + 68 + 79 = 395,395 / 5 = 79.0;/ 运算符总是得到浮点数,所以输出是 79.0 而不是 79。
math.ceil rounds up: 47 / 10 = 4.7, so 47 items need 5 pages, because the last page is only partly full. Integer division 47 // 10 gives 4 and loses the partial page. ceil lives in the math module, so it needs import math and the prefix math.; sum and round do not.math.ceil 向上取整:47 / 10 = 4.7,所以 47 项需要 5 页,因为最后一页不满。整数除法 47 // 10 得到 4,丢掉了不满的那一页。ceil 属于 math 模块,所以需要 import math 和前缀 math.;而 sum 和 round 不需要。
Common error: how round and int treat halves and negatives.常见错误:round 与 int 如何处理一半和负数。
Python 3 round sends an exact half to the nearest even integer: round(2.5) is 2 but round(3.5) is 4. For negatives, math.floor goes down to the next smaller integer (-4.7 becomes -5), while int simply cuts off the decimal part (-4.7 becomes -4). Why this works: each function is documented by its signature and one sentence; read the documentation instead of guessing what a rounding function does with a half or a negative number.Python 3 的 round 会把恰好一半的数舍入到最近的偶数:round(2.5) 是 2,而 round(3.5) 是 4。对于负数,math.floor 向下取到更小的整数(-4.7 变为 -5),而 int 只是去掉小数部分(-4.7 变为 -4)。原因:每个函数都由其签名和一句说明来记录;不要猜测取整函数如何处理一半或负数,应该阅读文档。
Name the module when you use a library function: math.sqrt(144), not sqrt(144), and put import math before it. abs, len, max, min, sum and round are built in and need no import. When a question asks for a number of pages or boxes, check whether a partial one still counts: that is the difference between math.ceil and //.
使用库函数时要写明模块:写 math.sqrt(144) 而不是 sqrt(144),并在它之前写 import math。abs、len、max、min、sum 和 round 是内置的,不需要导入。当题目要求页数或箱数时,要检查不满的一页或一箱是否也要计入:这就是 math.ceil 与 // 的区别。
Which of these need import math or another import: abs(-7), len("hat"), math.ceil(4.1), random.randint(1, 6)?下列哪些需要 import math 或其他导入:abs(-7)、len("hat")、math.ceil(4.1)、random.randint(1, 6)?
math.ceil(4.1) needs import math and random.randint(1, 6) needs import random. abs and len are built-in functions and need no import.
math.ceil(4.1) 需要 import math,random.randint(1, 6) 需要 import random。abs 和 len 是内置函数,不需要导入。
A hall seats 30 people per row. For 125 people, how many rows are needed? Write the Python expression and the value.一个大厅每排坐 30 人。125 人需要多少排?写出 Python 表达式及其值。
math.ceil(125 / 30). Since 125 / 30 is about 4.17, rounding up gives 5 rows; the fifth row is only partly used. 125 // 30 would give 4 and leave people without seats.
math.ceil(125 / 30)。125 / 30 约为 4.17,向上取整得 5 排;第五排只坐一部分。125 // 30 会得到 4,使一些人没有座位。
import math
print(round(3.5))
print(round(2.5))
print(int(-3.9))
print(math.floor(-3.9))
What does the program print, one value per line?程序逐行输出什么值?
4, 2, -3, -4. Python 3 round sends the half 3.5 to the even 4 and the half 2.5 to the even 2; int(-3.9) cuts off the decimals to give -3; math.floor(-3.9) goes down to -4.
依次为 4、2、-3、-4。Python 3 的 round 把一半的 3.5 舍入到偶数 4,把一半的 2.5 舍入到偶数 2;int(-3.9) 去掉小数部分得 -3;math.floor(-3.9) 向下取到 -4。
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" lists 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 questions that follow Ontario ICS3U A3.2 and AB CSE2110, 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 blurs the two ideas and is an incomplete answer.在遵循安大略 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 so that it is clear 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, is a clearer answer than a vague description.在关于模块化设计的 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 names 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 = 5 runs (without declaring global). What is the global x after the function returns?已知:x = 10(全局)。在函数内部,x = 5 运行(未声明 global)。函数返回后全局变量 x 是多少?global x inside the function, Python creates a new local variable x. The assignment x = 5 sets the local, not the global. The global x remains 10. (Had the line been x = x + 5, Python would raise UnboundLocalError, because assigning makes x local and its value is read before it is set.)在函数内没有 global x,Python 创建一个新的局部变量 x。赋值 x = 5 设置的是局部变量,而非全局变量。全局 x 仍为 10。(如果这一行是 x = x + 5,Python 会引发 UnboundLocalError,因为赋值使 x 成为局部变量,而它的值在被设置之前就被读取了。)global x, the assignment x = 5 creates a local variable. The global is unchanged, so it is still 10, not 15 or 5. This is why modifying globals inside functions requires explicit declaration.没有 global x,赋值 x = 5 创建一个局部变量。全局变量不变,仍是 10,而不是 15 或 5。这就是为什么在函数内修改全局变量需要显式声明。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 Practice 3.B / 🇨🇦 BC CP12解释过程抽象:说明为什么调用方只需知道函数的接口(名称、形参、返回类型)而不需要知道其实现。举一个例子。🇺🇸 AP CSP Practice 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) cover the concepts in this guide. 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 removes a common source of confusion in introductory programming.AP CSP 大概念 3 主题 3.12–3.14(调用过程、开发过程、库)涵盖本指南中的概念。AP CSA(Java 专项)从 Unit 1 起处处使用方法;此处教授的参数传递、返回值和作用域概念与 Java 方法的工作方式完全相同。在开始任一 AP 课程之前掌握本单元,可以消除入门编程中常见的困惑来源。
This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。
Common Questions常见问题
What is the difference between a parameter and an argument?形参和实参有什么区别?
A parameter is the placeholder name written in the function definition, while an argument is the actual value you pass in when you call the function. The parameter has no value until the function is called with an argument.形参是写在函数定义中的占位符名称,实参是你调用函数时传入的实际值。在用实参调用函数之前,形参没有值。
What is the difference between a local and a global variable?局部变量和全局变量有什么区别?
A local variable is created inside a function, is only visible there, and is destroyed when the function returns, while a global variable is created outside all functions and is visible everywhere. Best practice is to prefer local variables and pass data in through parameters.局部变量在函数内部创建,只在该函数中可见,函数返回时被销毁;全局变量在所有函数之外创建,处处可见。最佳做法是优先使用局部变量,并通过参数传入数据。
Why should I use functions instead of repeating code?为什么要用函数而不是重复写代码?
Functions let you define logic once and call it anywhere, so there is no copy-paste, and if the logic changes you fix one place and every caller gets the update. They also support modular design by splitting a big program into small, independently testable pieces.函数让你只定义一次逻辑就能到处调用,无需复制粘贴;逻辑改动时只改一处,所有调用方都会得到更新。它们还支持模块化设计,把大程序拆成可独立测试的小块。
Syllabus alignment & how to use this guide大纲对照与使用说明
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) covers 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 covered.§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; local/global is covered 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 named 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 要求你编写具有参数传递和正确作用域的函数。这两项技能本指南均完整涵盖。