← Course Hub← 课程主页 ← All Units← 返回单元列表
H I G H  S C H O O L  C O M P U T E R  S C I E N C E
Practice练习题

Functions and Modular Design函数与模块化设计

Practice Questions · AP CSP-Feeder · US / ON / BC / AB Styles练习题集 · AP CSP 衔接 · 美 / 安 / 卑 / 阿省风格

EASY MEDIUM HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC 🇨🇦 AB AP CSP-style MCQAP CSP 风格选择题 AP CSP-feeder FRQAP CSP 衔接简答题 ON Provincial-style安大略省考风格 BC Provincial-style卑诗省考风格 AB/Universal Applied阿省/通用应用题 Honors荣誉级


Name:姓名:Date:日期:
PART I  ·  SHORT RESPONSE第一部分  ·  短答题AP CSP-style MCQ + ON/BC short answer · 25 marksAP CSP 风格选择题 + 安/卑省考短答 · 共 25 分

Section A · Short ResponseA 部分 · 短答题

Questions mix multiple-choice and short-answer items. For MCQs, circle the letter. For short-answer items, write functions in pseudocode or Python with correct indentation. Trace code by hand: write each variable's value at each step before answering.本部分包含选择题与短答题。选择题请圈出字母。短答题用伪代码或 Python 书写函数,缩进须正确。手工追踪代码:作答前写出每一步每个变量的值。

Q1 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §1 Why Functions?为什么要用函数? · AP CSP AAP-3.B [3 marks][3 分]

A student copies the same 15-line calculation into four different places in their program. Later, they discover a bug in that calculation. What is the main disadvantage of this approach compared to using a function?一名学生将同一段 15 行计算复制到程序的四个不同地方。后来他们在该计算中发现了一个错误。与使用函数相比,这种做法的主要缺点是什么?

  1. (A) The program will run more slowly because of the repeated code程序因重复代码而运行更慢
  2. (B) The bug must be fixed in all four copies; missing even one creates inconsistency必须在全部四处修复该错误;漏掉任何一处都会导致不一致
  3. (C) Python does not allow duplicate code in the same programPython 不允许同一程序中出现重复代码
  4. (D) The program will use more memory than a single function would程序会比使用单一函数消耗更多内存
Q2 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §2 Defining and Calling Functions定义与调用函数 · AP CSP AAP-3.B [3 marks][3 分]

What does the following program output?以下程序输出什么?

def say_hello(name):
    print("Hello, " + name + "!")

say_hello("Sam")
say_hello("Alex")
  1. (A) Nothing: the function is defined but never called什么都没有:函数定义了但从未被调用
  2. (B) Hello, name! printed twice打印两次
  3. (C) Hello, Sam! then然后 Hello, Alex!
  4. (D) Hello, Alex! then然后 Hello, Sam!
Q3 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §3 Parameters and Arguments形参与实参 · ICS3U A3.2 [5 marks][5 分]

Consider the following function and calls.考察以下函数及调用。

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(3, 2)
OUTPUT power(2, 4)
(a) Identify the parameters of the function power.指出函数 power 的形参。 [1]
(b) For the call power(3, 2), state the argument bound to each parameter and trace the loop to find the return value.对于调用 power(3, 2),写出绑定到每个形参的实参,并追踪循环以求出返回值。 [3]
(c) State the output of power(2, 4) without full trace; justify in one sentence.无需完整追踪,写出 power(2, 4) 的输出;用一句话说明理由。 [1]
Q4 MEDIUM 🇨🇦 AB AB/Universal Applied阿省/通用应用题 §4 Return Values返回值 · CSE2110 3.2 [7 marks][7 分]

A programmer writes a function to classify a score and uses it in a program.程序员编写了一个分类成绩的函数,并在程序中使用它。

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

SET result TO grade(82)
OUTPUT result
OUTPUT grade(55)
(a) Trace the call grade(82) step by step. Identify which RETURN executes and state the value returned.逐步追踪调用 grade(82)。指出哪条 RETURN 语句执行,写出返回的值。 [3]
(b) State the two values output by the program.写出程序输出的两个值。 [2]
(c) Explain why the remaining IF statements do NOT execute once the first matching RETURN is reached.解释为什么一旦第一个匹配的 RETURN 执行,其余 IF 语句不再执行。 [1]
(d) The function grade is a value-returning function. Describe one difference between a value-returning function and a procedure (void function).grade 是有返回值的函数。描述有返回值的函数与过程(无返回值函数)之间的一个区别。 [1]
Q5 MEDIUM 🇨🇦 BC BC Provincial-style卑诗省考风格 §5 Variable Scope变量作用域 · ICS3U A3.2 [7 marks][7 分]

Study the following program carefully.仔细研究以下程序。

SET score TO 50        # global variable

FUNCTION update():
    SET score TO score + 10
    RETURN score
END FUNCTION

OUTPUT score            # Line A
OUTPUT update()         # Line B  (Python: uses global keyword inside)
OUTPUT score            # Line C
(a) State the output at Line A. Explain why in one sentence.写出第 A 行的输出。用一句话解释原因。 [2]
(b) Assuming the function modifies the global score (using the global keyword in Python), state the output at Line B and Line C.假设函数使用 global 关键字修改了全局变量 score,写出第 B 行和第 C 行的输出。 [2]
(c) Explain why it is better practice to pass score as a parameter and return the new value instead of modifying a global. Give one specific risk of relying on global state.解释为什么将 score 作为形参传入并返回新值比修改全局变量更好。给出依赖全局状态的一个具体风险。 [2]
(d) If two functions each have their own local variable named count, can they interfere with each other? Answer in one sentence.如果两个函数各自都有一个名为 count 的局部变量,它们会互相干扰吗?用一句话回答。 [1]
PART II  ·  EXTENDED RESPONSE第二部分  ·  简答题AP CSP-feeder FRQ + Honors · 30 marksAP CSP 衔接简答题 + 荣誉级 · 共 30 分

Section B · Extended ResponseB 部分 · 简答题

Write pseudocode or Python clearly, with correct indentation. For each trace, show every variable value at each step. For written questions, two complete sentences earn full marks. Trace function calls by writing the parameter bindings before entering the function body.伪代码或 Python 须清晰书写,缩进正确。每次追踪须写出每一步每个变量的值。书面解答题用两句完整句子即可满分。追踪函数调用时,先写出形参绑定,再进入函数体。

Q6 EASY 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §6 Modular Design模块化设计 · CSTA 3A-AP-17 [7 marks][7 分]

A programmer decomposes a grade-report program into four functions as shown below. The main program uses only four lines.程序员将成绩报告程序分解为如下四个函数。主程序只有四行。

FUNCTION get_scores():
    -- reads 5 scores and returns them as a list
    ...
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)
(a) Which two of the four functions are procedures (void functions, no return value)? Justify your answer.四个函数中哪两个是过程(无返回值函数)?说明理由。 [2]
(b) If the scores are [85, 90, 78, 92, 80], trace the call compute_average(scores) and state the return value.如果成绩为 [85, 90, 78, 92, 80],追踪调用 compute_average(scores) 并写出返回值。 [3]
(c) Explain one benefit of decomposing the program into these four functions rather than writing all the code in one block.解释将程序分解为这四个函数(而非写在一整块代码中)的一个好处。 [2]
Q7 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §2 + §3 Calling Functions + Parameter Passing调用函数 + 参数传递 · ICS3U A3.2 [8 marks][8 分]

Study the following two functions and the code that calls them.研究以下两个函数及调用它们的代码。

def double(n):
    return n * 2

def add_and_double(a, b):
    total = a + b
    return double(total)

x = add_and_double(3, 7)
print(x)
print(add_and_double(5, 5))
(a) For the call add_and_double(3, 7), state the argument bound to each parameter and trace the function to determine the return value.对于调用 add_and_double(3, 7),写出绑定到每个形参的实参,并追踪函数以确定返回值。 [3]
(b) Write the two values printed by the program.写出程序打印的两个值。 [2]
(c) The function add_and_double calls double internally. Explain in one sentence what this demonstrates about function reuse.add_and_double 在内部调用 double。用一句话解释这说明了函数复用的什么特点。 [1]
(d) If the student modifies double to multiply by 3 instead of 2, state the new output of both print statements.如果学生将 double 修改为乘以 3 而非 2,写出两条 print 语句的新输出。 [2]
Q8 HARD 🇨🇦 BC 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §4 + §5 Return Values + Scope返回值 + 作用域 · CSE2110 3.3 / ICS3U A3.2 [8 marks][8 分]

Study the following program carefully. Note the local variable named result inside each function.仔细研究以下程序。注意每个函数内部名为 result 的局部变量。

def square(n):
    result = n * n
    return result

def cube(n):
    result = n * n * n
    return result

a = square(4)
b = cube(3)
print(a)
print(b)
print(a + b)
(a) Trace the call square(4): state the value bound to n, compute result, and state the return value.追踪调用 square(4):写出绑定到 n 的值,计算 result,写出返回值。 [2]
(b) State the three values printed by the program.写出程序打印的三个值。 [3]
(c) Both square and cube have a local variable called result. Explain in one sentence why these two variables do not interfere with each other.squarecube 都有名为 result 的局部变量。用一句话解释这两个变量为什么互不干扰。 [1]
(d) Rewrite square so that it uses a global variable result instead of a local one (add the global declaration). Then explain one reason why this version is worse than the original.重写 square,使其使用全局变量 result 而非局部变量(添加 global 声明)。然后解释该版本比原版差的一个原因。 [2]
Q9 HARD Honors荣誉级 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §5 + §6 Scope + Coupling / Cohesion作用域 + 耦合与内聚 · CSE2110 3.4 / ICS4U C1.3 [7 marks][7 分]

The two programs below compute the same result but use different designs. Program A uses a shared global variable; Program B passes data only through parameters and return values.以下两个程序计算相同的结果,但使用了不同的设计。程序 A 使用共享的全局变量;程序 B 仅通过形参和返回值传递数据。

Program A (global state):程序 A(全局状态):

total = 0

def add_item(price):
    global total
    total = total + price

add_item(15)
add_item(30)
print(total)

Program B (parameter-based):程序 B(基于参数):

def add_item(running_total, price):
    return running_total + price

t = 0
t = add_item(t, 15)
t = add_item(t, 30)
print(t)
(a) Trace both programs and confirm they output the same value. State that value.追踪两个程序,确认它们输出相同的值。写出该值。 [2]
(b) In Program A, what happens if you call add_item(10) a second time in a different part of the program? Explain why the result depends on hidden state.在程序 A 中,如果在程序的另一处再次调用 add_item(10),会发生什么?解释为什么结果依赖于隐藏状态。 [2]
(c) Explain why Program B's design is preferred in modular programs. Use the terms coupling and cohesion in your answer (AB CSE2110 outcome 3.4).解释为什么在模块化程序中首选程序 B 的设计。在回答中使用术语耦合(coupling)和内聚(cohesion)(AB CSE2110 结果 3.4)。 [2]
(d) Give one real-world scenario where using a global variable would be appropriate (e.g., a program-wide configuration setting). Justify your answer in one sentence.举一个使用全局变量合适的真实场景(如程序范围的配置设置)。用一句话说明理由。 [1]
PART III  ·  MODELING / APPLIED第三部分  ·  建模与应用Universal / multi-region applied · 25 marks通用/多地区应用题 · 共 25 分

Section C · Modeling and ApplicationsC 部分 · 建模与应用

Read each scenario carefully before writing code. For pseudocode, use standard block format (FUNCTION/END FUNCTION, IF/THEN/END IF). For Python, show correct indentation. Each question asks you to design, trace, or extend functions; always state the return value or output explicitly.动笔前仔细阅读每个场景。伪代码使用标准块格式(FUNCTION/END FUNCTION、IF/THEN/END IF)。Python 须正确缩进。每题要求设计、追踪或扩展函数;务必明确写出返回值或输出。

Q10 MEDIUM 🇺🇸 US 🇨🇦 ON AP CSP-feeder FRQAP CSP 衔接简答题 §1 + §2 + §3 Writing Functions from Scratch从零编写函数 · ICS3U A3.1 / CSTA 3A-AP-18 [8 marks][8 分]

A student needs a program that converts a temperature in Celsius to Fahrenheit using the formula F = C x 9/5 + 32. The same conversion is needed in three different places.一名学生需要一个程序,使用公式 F = C x 9/5 + 32 将摄氏温度转换为华氏温度。同一转换在三个不同地方都需要用到。

(a) Write the function to_fahrenheit(celsius) in pseudocode. It must accept one parameter and return the converted value.用伪代码编写函数 to_fahrenheit(celsius)。它必须接受一个形参并返回转换后的值。 [3]
(b) Verify your function by hand-tracing to_fahrenheit(0) and to_fahrenheit(100). State the two return values.手工追踪 to_fahrenheit(0)to_fahrenheit(100) 以验证你的函数。写出两个返回值。 [2]
(c) Rewrite the same function in Python.用 Python 重写相同的函数。 [2]
(d) Explain in one sentence why placing this formula in a function (rather than copying it three times) follows the DRY (Don't Repeat Yourself) principle.用一句话解释为什么将该公式放入函数中(而非复制三次)遵循了 DRY(不要重复自己)原则。 [1]
Q11 MEDIUM 🇨🇦 ON 🇨🇦 BC ON Provincial-style安大略省考风格 §6 + §7 Modular Design + Built-in Functions模块化设计 + 内置函数 · ICS3U A3.1 / B2.3 [9 marks][9 分]

A student must write a program that computes statistics (minimum, maximum, average) for a list of quiz scores, then displays a summary. They choose a modular design with one function per task.一名学生需要编写一个程序,计算一组测验成绩的统计数据(最小值、最大值、平均值),然后显示摘要。他们选择每个任务一个函数的模块化设计。

scores = [72, 88, 65, 91, 78]

def find_min(data):
    return min(data)        # uses built-in min()

def find_max(data):
    return max(data)        # uses built-in max()

def find_average(data):
    return sum(data) / len(data)   # uses built-in sum() and len()

def display_summary(data):
    print("Min:", find_min(data))
    print("Max:", find_max(data))
    print("Avg:", find_average(data))

display_summary(scores)
(a) State the three values printed by display_summary(scores). Show your calculations for the average.写出 display_summary(scores) 打印的三个值。展示平均值的计算过程。 [4]
(b) The built-in functions min(), max(), sum(), and len() are used in this program. Explain why using them instead of writing custom loops illustrates the principle described in CSTA 3B-AP-16.该程序使用了内置函数 min()max()sum()len()。解释为什么使用它们(而非编写自定义循环)体现了 CSTA 3B-AP-16 所描述的原则。 [2]
(c) The student wants to add a function find_range(data) that returns the difference between the maximum and minimum. Write this function in Python. It should call find_max and find_min instead of calling max() and min() directly, to demonstrate function reuse.学生想添加一个函数 find_range(data),返回最大值与最小值之差。用 Python 编写此函数。它应调用 find_maxfind_min(而非直接调用 max()min()),以展示函数复用。 [2]
(d) State the return value of find_range(scores) for the given list.对于给定列表,写出 find_range(scores) 的返回值。 [1]
Q12 HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC AP CSP-feeder FRQAP CSP 衔接简答题 All sections · Top-Down Design + Extension全节综合 · 自顶向下设计与扩展 · CSTA 3A-AP-17 / ICS3U B2.3 [8 marks][8 分]

A student is building a tip calculator. They use top-down design: the main program reads three inputs (bill amount, tip percentage, number of people) and calls three helper functions to do the work.一名学生正在构建小费计算器。他们采用自顶向下设计:主程序读取三个输入(账单金额、小费百分比、人数),并调用三个辅助函数完成工作。

FUNCTION compute_tip(bill, percent):
    RETURN bill * percent / 100
END FUNCTION

FUNCTION compute_total(bill, tip):
    RETURN bill + tip
END FUNCTION

FUNCTION per_person(total, people):
    RETURN total / people
END FUNCTION

-- Main program
SET bill    TO 120
SET percent TO 15
SET people  TO 4

SET tip     TO compute_tip(bill, percent)
SET total   TO compute_total(bill, tip)
SET share   TO per_person(total, people)
OUTPUT "Each person pays: " + share
(a) Trace the three function calls in order. Show the argument bindings and compute the return value of each call. State the final output.按顺序追踪三个函数调用。写出实参绑定并计算每次调用的返回值。写出最终输出。 [4]
(b) The student wants to add a function apply_discount(total, discount_pct) that reduces the total by a given percentage before splitting. Write the function in pseudocode and state the new share if discount_pct = 10 is applied to the total computed in part (a).学生想添加一个函数 apply_discount(total, discount_pct),在拆分之前按给定百分比减少总额。用伪代码编写该函数,并写出对 (a) 中计算的总额应用 discount_pct = 10 后的新人均分摊额。 [3]
(c) Identify one way the top-down structure of this program demonstrates the single-responsibility rule.指出该程序的自顶向下结构在哪个方面体现了单一职责规则。 [1]

🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP3A-AP-17 · 3A-AP-18 · AAP-3.B
🇨🇦 Ontario安大略ICS3U A3.1 · A3.2 · B2.3
🇨🇦 British Columbia不列颠哥伦比亚CS 11 / CP11: functions, modularity, pre-built librariesCS 11 / CP11:函数、模块化、预建库
🇨🇦 Alberta阿尔伯塔CSE2110: outcomes 3.2, 3.3, 3.3.3, 3.4CSE2110:结果 3.2、3.3、3.3.3、3.4

Full Syllabus Map in Study Guide: ../Study Guides/Unit_4_Functions_and_Modular_Design.html. CS has no AB standalone diploma exam; AB framing uses CSE2110 outcomes.完整大纲对照见学习指南:../Study Guides/Unit_4_Functions_and_Modular_Design.html。CS 无独立 AB 毕业考;AB 题使用 CSE2110 结果框架。