← 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
Solutions答案与解析

Programming Fundamentals编程基础

Full Worked Solutions · 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荣誉级


PART I  ·  SHORT RESPONSE  ·  SOLUTIONS第一部分  ·  短答题  ·  答案AP CSP-style MCQ + ON/BC short answer · 25 marksAP CSP 风格选择题 + 安/卑省考短答 · 共 25 分

Section A · Worked SolutionsA 部分 · 解析

Each solution card shows the answer, sub-part marks (M1 method, A1 answer), and an insight block connecting the result to a broader principle. Mark allocations follow the companion Practice file.每张解答卡显示答案、每小问得分(M1 方法分,A1 答案分)以及将结论与更广泛原理联系的洞察块。分值分配与配套练习题一致。

Q1 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §1 Variables and Assignment变量与赋值 · AP CSP AAP-1.B [3 marks][3 分]

After the following three lines execute, what is the value of y?以下三行执行后,y 的值是什么?

x = 4
y = x + 3
x = 10
  1. (A) 10
  2. (B) 13
  3. (C) 7
  4. (D) 4
Answer:答案: (C) 7

When line 2 executes, x holds 4, so Python evaluates 4 + 3 = 7 and stores that value in y.第 2 行执行时,x4,Python 计算 4 + 3 = 7 并将该值存入 y A1

Line 3 (x = 10) reassigns x but does NOT retroactively change y. Assignment captures the value at the moment of execution.第 3 行 (x = 10) 重新赋值 x,但不会追溯修改 y。赋值在执行时刻捕获值。 A1

Distractors: (A) 10 confuses x's final value with y; (B) 13 assumes y "updates" when x changes; (D) 4 mistakes x's initial value for y.干扰项:(A) 10 将 x 的最终值混淆为 y;(B) 13 误以为 x 变化时 y 会同步更新;(D) 4 将 x 的初始值误作 y。 M1

Insight:洞察: Python variables store values, not references to other variables. Once y = x + 3 is evaluated, y is independent of x. This is a fundamental distinction between assignment and aliasing.Python 变量存储的是,而非对其他变量的引用。一旦 y = x + 3 被求值,y 就独立于 x 了。这是赋值与别名的根本区别。
Q2 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §2 Data Types数据类型 · AP CSP 2.1 / ON ICS3U A1.1 [3 marks][3 分]

Which of the following is the correct data type for the value "3.14" (with quotes) in Python?以下哪项是 Python 中 "3.14"(带引号)的正确数据类型?

  1. (A) int整数 (int)
  2. (B) float浮点数 (float)
  3. (C) str字符串 (str)
  4. (D) bool布尔 (bool)
Answer:答案: (C) str

Quotation marks always create a string in Python. Even though the content looks like a number, the type is determined by the syntax, not the content.引号在 Python 中始终创建字符串。即使内容看起来像数字,类型由语法决定,而非内容。 A1

Verify: type("3.14") returns <class 'str'>. The numeric value 3.14 (no quotes) would be a float.验证:type("3.14") 返回 <class 'str'>。数值 3.14(无引号)才是 float M1

Distractors: (A) int requires no decimal; (B) float is the unquoted literal; (D) bool only holds True/False.干扰项:(A) int 无小数点;(B) float 是不带引号的字面量;(D) bool 仅存储 True/False。 A1

Insight:洞察: Data type is determined by the delimiter in source code, not by what the value looks like. Quotes always mean str. This distinction matters deeply when doing arithmetic: "3.14" + 1 raises a TypeError.数据类型由源代码中的定界符决定,而非值的外观。引号始终意味着 str。这一区别在做算术时至关重要:"3.14" + 1 会引发 TypeError
Q3 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §3 Input and Output输入与输出 · ICS3U A2.1 / AB CSE1110 2.4.5 [7 marks][7 分]

A student writes the following program. The user types 5 at the prompt.一名学生编写了以下程序。用户在提示符处输入 5

n = input("Enter a number: ")
result = n * 2
print(result)
(a) State the data type of n after line 1 executes. Explain why.写出第 1 行执行后 n 的数据类型。解释原因。 [2]
(b) State the exact value that result holds after line 2 executes. State its data type too.写出第 2 行执行后 result 保存的精确值。同时写出其数据类型。 [2]
(c) The student wants result to be 10 (integer). Write the corrected line 1 that fixes the bug.学生希望 result10(整数)。写出修正后的第 1 行以修复该错误。 [2]
(d) State the Python function used to display output on the screen.写出 Python 中用于在屏幕上显示输出的函数。 [1]
Answers: (a) str  |  (b) "55", str  |  (c) n = int(input(...))  |  (d) print()答案:(a) str  |  (b) "55",str  |  (c) n = int(input(...))  |  (d) print()

(a) A1+M1

n is of type str. The built-in input() function always returns a string, regardless of what the user types. When the user types 5, Python stores the character sequence "5", not the integer 5.n 的类型是 str。内置函数 input() 始终返回字符串,无论用户输入什么。当用户输入 5 时,Python 存储字符序列 "5",而非整数 5

(b) A1+A1

Value: "55" (a two-character string). Type: str. Because n is a string, the * operator performs string repetition: "5" * 2 = "55".值:"55"(两字符字符串)。类型:str。因为 n 是字符串,* 运算符执行字符串重复:"5" * 2 = "55"

(c) A1+A1

n = int(input("Enter a number: "))

Wrapping input() in int() converts the returned string to an integer before assignment. Now n = 5 (int), and n * 2 = 10.input() 包裹在 int() 中,在赋值前将返回的字符串转换为整数。现在 n = 5 (int),n * 2 = 10

(d) A1

print()

Insight:洞察: The input()-always-returns-str rule is the single most common source of bugs for beginners. The fix is always to wrap with the target type conversion: int(input(...)), float(input(...)), etc. Never assume a number from input without explicitly converting.input() 始终返回字符串这一规则是初学者最常见的错误来源。修复方法始终是将其包裹在目标类型转换中:int(input(...))float(input(...)) 等。切勿假定从 input 获得的是数字,而不显式转换。
Q4 MEDIUM 🇨🇦 BC 🇨🇦 AB AB/Universal Applied阿省/通用应用题 §4 Operators运算符 · BC CS10 / AB CSE1110 2.4.6 [6 marks][6 分]

Given a = 17 and b = 5, evaluate each expression below.给定 a = 17b = 5,计算以下每个表达式。

(a) State the value of a // b and its data type.写出 a // b 的值及其数据类型。 [2]
(b) State the value of a % b and explain what it represents.写出 a % b 的值,并解释它代表什么。 [2]
(c) Evaluate the expression a > 10 and b == 5 and state whether the result is True or False. Show your reasoning.计算表达式 a > 10 and b == 5,写出结果是 True 还是 False。写出推理过程。 [2]
Answers: (a) 3, int  |  (b) 2, remainder  |  (c) True答案:(a) 3,int  |  (b) 2,余数  |  (c) True

(a) A1+A1

17 // 5 = 3. Floor division discards the remainder. Data type: int (integer // integer returns integer).17 // 5 = 3。整除运算舍弃余数。数据类型:int(整数整除整数返回整数)。

(b) A1+A1

17 % 5 = 2. The modulo operator returns the remainder after division: 17 = 5 * 3 + 2. It represents how much is left over after evenly dividing 17 by 5.17 % 5 = 2。取模运算符返回除法后的余数17 = 5 * 3 + 2。它表示将 17 均分为 5 份后剩余的量。

(c) M1+A1

a > 10 evaluates to 17 > 10 = True. b == 5 evaluates to 5 == 5 = True. True and True = True. The overall expression is True.a > 10 计算结果为 17 > 10 = Trueb == 5 计算结果为 5 == 5 = TrueTrue and True = True。整个表达式为 True

Insight:洞察: // and % are complementary operators: a = (a//b)*b + (a%b) always holds. This pair is used everywhere: converting seconds to minutes/seconds, checking even/odd (n % 2), cycling indices, and more. Mastering them removes the need for division in many integer contexts.//% 是互补运算符:a = (a//b)*b + (a%b) 恒成立。这对运算随处可见:将秒转换为分钟/秒、判断奇偶(n % 2)、循环索引等。掌握它们可以在许多整数场景中避免使用除法。
Q5 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §5 Type Conversion and Casting类型转换 · ICS3U A1.3 / AB CSE1110 2.4.3 [6 marks][6 分]

For each line of Python below, state the result and its data type. If the line raises an error, name the error.对以下每行 Python,写出结果及其数据类型。若该行引发错误,请说明错误名称。

(a) int(7.9) [2]
(b) str(42) + " points" [2]
(c) int("3.9") [2]
Answers: (a) 7, int  |  (b) "42 points", str  |  (c) ValueError答案:(a) 7,int  |  (b) "42 points",str  |  (c) ValueError

(a) A1+A1

int(7.9) returns 7, type int. Python's int() truncates (discards the fractional part) rather than rounding. int(7.9) and int(7.1) both return 7.int(7.9) 返回 7,类型 int。Python 的 int() 截断(丢弃小数部分)而非四舍五入。int(7.9)int(7.1) 都返回 7

(b) A1+A1

str(42) converts the integer to the string "42". Concatenating "42" + " points" gives "42 points", type str.str(42) 将整数转换为字符串 "42"。拼接 "42" + " points" 得到 "42 points",类型 str

(c) A1+A1

int("3.9") raises a ValueError. Python's int() can parse integer strings like "3", but not decimal strings like "3.9". To convert "3.9" to an integer, first use float("3.9") then int(): int(float("3.9")) = 3.int("3.9") 引发 ValueError。Python 的 int() 可以解析整数字符串(如 "3"),但无法解析小数字符串(如 "3.9")。若要将 "3.9" 转换为整数,需先用 float("3.9") 再用 int()int(float("3.9")) = 3

Insight:洞察: Type conversion is not a free operation: it can fail at runtime. int() rejects strings with a decimal point. The safe pattern for reading a decimal from the user is float(input(...)), then cast to int only if needed. Never assume a string is numeric without validation.类型转换不是免费操作:它可能在运行时失败。int() 拒绝含小数点的字符串。从用户处读取小数的安全模式是 float(input(...)),再仅在需要时转换为 int。切勿在未验证的情况下假设字符串是数值。
PART II  ·  EXTENDED RESPONSE  ·  SOLUTIONS第二部分  ·  简答题  ·  答案AP CSP-feeder FRQ + Honors · 30 marksAP CSP 衔接简答题 + 荣誉级 · 共 30 分

Section B · Worked SolutionsB 部分 · 解析

Each solution shows sub-part mark breakdowns with M1 (method) and A1 (answer) marks. Full credit requires showing trace steps, data types, and reasoning, not just a final answer.每道解析均显示小问分值明细,含 M1(方法分)和 A1(答案分)。满分须写出追踪步骤、数据类型及推理过程,而非仅给出最终答案。

Q6 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §6 Constants and Naming Conventions常量与命名规范 · ON ICS3U A1.1 / AB CSE1110 2.4.4 [5 marks][5 分]

Answer each naming question below.回答以下每道命名问题。

(a) Which variable name follows Python's snake_case convention for a variable storing a student's total score?哪个变量名遵循 Python 的 snake_case 规范,用于存储学生的总分? [1]
  1. (A) TotalScore
  2. (B) total_score
  3. (C) TOTAL_SCORE
  4. (D) ts
(b) A tax-rate value of 0.13 should not change during the program. Write the correctly named Python line that declares it as a constant.税率值 0.13 在程序运行中不应改变。写出将其声明为常量的正确命名 Python 语句。 [1]
(c) Explain in two sentences why using TAX_RATE = 0.13 instead of the literal 0.13 throughout the code is better practice.用两句话解释为什么在代码中使用 TAX_RATE = 0.13 而不是字面值 0.13 是更好的实践。 [2]
(d) State the naming convention for Python class names (not variables, not constants).写出 Python 类名(非变量、非常量)的命名规范。 [1]
Answers: (a) (B) total_score  |  (b) TAX_RATE = 0.13  |  (c) readability + maintainability  |  (d) PascalCase答案:(a) (B) total_score  |  (b) TAX_RATE = 0.13  |  (c) 可读性 + 可维护性  |  (d) PascalCase 大驼峰

(a) A1

(B) total_score. Python's PEP 8 style guide specifies lowercase words separated by underscores for variable names. (A) is PascalCase (used for classes); (C) is SCREAMING_SNAKE_CASE (used for constants); (D) is too abbreviated.(B) total_score。Python 的 PEP 8 风格指南规定变量名使用下划线分隔的小写单词。(A) 是 PascalCase(用于类);(C) 是全大写蛇形(用于常量);(D) 缩写过短。

(b) A1

TAX_RATE = 0.13

Constants are named in SCREAMING_SNAKE_CASE (all uppercase with underscores). Note: Python does not enforce immutability, but the naming convention signals to other programmers that this value should not be changed.常量以全大写蛇形命名(SCREAMING_SNAKE_CASE)。注意:Python 不强制不可变性,但命名规范向其他程序员表明该值不应被修改。

(c) A1+A1

Using a named constant improves readability: TAX_RATE clearly communicates the purpose of the value. It also improves maintainability: if the tax rate changes, you update only one line instead of searching for every occurrence of 0.13 in the code.使用具名常量提高了可读性TAX_RATE 清晰传达了值的用途。它还提高了可维护性:若税率变化,只需更新一行,而非搜索代码中每处 0.13

(d) A1

PascalCase (also called UpperCamelCase): each word starts with a capital letter, no underscores. Example: StudentRecord, BankAccount.PascalCase(也称大驼峰命名法):每个单词首字母大写,无下划线。示例:StudentRecordBankAccount

Insight:洞察: Naming conventions (snake_case for variables, SCREAMING_SNAKE_CASE for constants, PascalCase for classes) are enforced by community convention (PEP 8) rather than the Python interpreter. Violating them does not cause errors, but it signals poor craft and makes code harder to maintain at scale. Professional code always follows these conventions.命名规范(变量用 snake_case,常量用 SCREAMING_SNAKE_CASE,类用 PascalCase)由社区约定(PEP 8)而非 Python 解释器强制执行。违反它们不会导致错误,但表明工艺不佳,且使大规模代码难以维护。专业代码始终遵循这些规范。
Q7 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §1 + §3 Variables, Assignment, and I/O变量、赋值与输入输出 · ICS3U A1.3 / A2.1 [8 marks][8 分]

A student writes a program to swap two variables and then print the result. Assume the user types 10 for the first prompt and 20 for the second.一名学生编写程序来交换两个变量并打印结果。假设用户第一个提示符输入 10,第二个输入 20

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
temp = a
a = b
b = temp
print(a, b)
(a) Trace the program line by line. For each of lines 3-5, state the value of a, b, and temp after that line executes.逐行追踪程序。对第 3-5 行,写出该行执行后 abtemp 的值。 [3]
(b) State the output of line 6.写出第 6 行的输出。 [1]
(c) Explain why a temp variable is required for the swap. What would happen if you wrote a = b followed directly by b = a without using temp?解释为什么交换时需要 temp 变量。若直接写 a = b 然后 b = a 而不使用 temp,会发生什么? [2]
(d) Rewrite the swap as a single Python line using tuple unpacking. State the line.用元组解包将交换改写为一行 Python。写出该行。 [2]
Answers: (a) trace table below  |  (b) 20 10  |  (c) a's original value is lost  |  (d) a, b = b, a答案:(a) 见追踪表  |  (b) 20 10  |  (c) a 的原始值丢失  |  (d) a, b = b, a

(a) M1+M1+A1

After lines 1-2: a = 10, b = 20.第 1-2 行后:a = 10, b = 20

  • Line 3: temp = a -- a = 10, b = 20, temp = 10第 3 行:temp = a -- a = 10, b = 20, temp = 10
  • Line 4: a = b -- a = 20, b = 20, temp = 10第 4 行:a = b -- a = 20, b = 20, temp = 10
  • Line 5: b = temp -- a = 20, b = 10, temp = 10第 5 行:b = temp -- a = 20, b = 10, temp = 10

(b) A1

Output: 20 10. Python's print(a, b) prints values separated by a space.输出:20 10。Python 的 print(a, b) 用空格分隔打印各值。

(c) A1+A1

Without temp: a = b overwrites a (value 10) with b's value (20). Then b = a copies 20 back into b. Both variables end up holding 20 -- the original value of a (10) is permanently lost. temp preserves a's original value before it is overwritten.若没有 tempa = b 用 b 的值 (20) 覆盖了 a(值 10)。然后 b = a 将 20 复制回 b。两个变量最终都保存 20 -- a 的原始值 (10) 永久丢失。temp 在 a 被覆盖之前保存了其原始值。

(d) A1+A1

a, b = b, a

Python evaluates the right side (b, a) as a tuple (20, 10) first, then unpacks it into a and b simultaneously. No temporary variable is needed.Python 先将右侧 (b, a) 求值为元组 (20, 10),再同时解包到 ab 中。无需临时变量。

Insight:洞察: The three-variable swap is a classic algorithm pattern that appears in sorting (bubble sort swaps adjacent elements) and many other contexts. The tuple-unpacking idiom a, b = b, a is Pythonic and more elegant, but understanding the temp-variable version teaches a transferable pattern that works in every language.三变量交换是出现在排序(冒泡排序交换相邻元素)等许多场景中的经典算法模式。元组解包写法 a, b = b, a 是 Python 风格的优雅写法,但理解临时变量版本可学到在每种语言中都通用的可迁移模式。
Q8 HARD 🇨🇦 BC 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §4 + §5 Operators and Type Conversion — Debugging运算符与类型转换——调试 · BC CS10 / AB CSE1110 2.4.3 / 2.4.6 [8 marks][8 分]

Each buggy program below contains one or more errors. Identify the error(s) and write the corrected code.以下每个有问题的程序包含一个或多个错误。识别错误,并写出更正后的代码。

Program A:程序 A:

score = input("Enter score: ")
bonus = score + 10
print("Final score:", bonus)

Program B:程序 B:

price = float(input("Enter price: "))
message = "Total is " + price
print(message)
(a) Identify the error in Program A. Name the Python exception it raises and explain why.识别程序 A 中的错误。说明它引发的 Python 异常名称及原因。 [2]
(b) Write the corrected Program A. The corrected version should output Final score: 95 when the user enters 85.写出更正后的程序 A。当用户输入 85 时,更正版应输出 Final score: 95 [2]
(c) Identify the error in Program B. Name the exception and explain the fix needed.识别程序 B 中的错误。说明异常名称,并解释所需修复。 [2]
(d) Write the corrected Program B line that builds the message string. You may use either str() concatenation or an f-string.写出更正后的程序 B 中构建消息字符串的那一行。可以使用 str() 拼接或 f 字符串。 [2]
Answers: (a) TypeError, str + int  |  (b) score = int(input(...)); bonus = score + 10  |  (c) TypeError, str + float  |  (d) see corrected line答案:(a) TypeError,str + int  |  (b) score = int(input(...)); bonus = score + 10  |  (c) TypeError,str + float  |  (d) 见更正行

(a) A1+A1

Program A raises a TypeError. score = input(...) returns a str. The expression score + 10 attempts to add a string to an integer, which Python does not allow. Error message: can only concatenate str (not "int") to str.程序 A 引发 TypeErrorscore = input(...) 返回 str。表达式 score + 10 尝试将字符串与整数相加,Python 不允许此操作。错误信息:can only concatenate str (not "int") to str

(b) A1+A1

score = int(input("Enter score: "))
bonus = score + 10
print("Final score:", bonus)

Converting the input to int first fixes the type mismatch. For input 85: bonus = 85 + 10 = 95. Output: Final score: 95.先将输入转换为 int 修复了类型不匹配。对于输入 85:bonus = 85 + 10 = 95。输出:Final score: 95

(c) A1+A1

Program B raises a TypeError. price is a float (correctly converted). The expression "Total is " + price attempts to concatenate a string and a float, which Python does not allow. The fix is to convert price to a string before concatenating.程序 B 引发 TypeErrorpricefloat(已正确转换)。表达式 "Total is " + price 尝试拼接字符串与浮点数,Python 不允许。修复方法是拼接前将 price 转换为字符串。

(d) A1+A1

Using str() concatenation:使用 str() 拼接:

message = "Total is " + str(price)

Or using an f-string:或使用 f 字符串:

message = f"Total is {price}"
Insight:洞察: TypeError in Python almost always means a type mismatch in an expression. The two most common forms are: (1) numeric-string arithmetic (str + int) and (2) string concatenation with a non-string (str + float). The fix is always explicit conversion. F-strings avoid this entirely by handling the conversion internally.Python 中的 TypeError 几乎总意味着表达式中的类型不匹配。最常见的两种形式:(1) 数字-字符串算术(str + int);(2) 字符串与非字符串拼接(str + float)。修复方法始终是显式转换。F 字符串通过内部处理转换完全避免了这一问题。
Q9 HARD Honors荣誉级 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §7 First Program — IPO design and edge cases编写第一个程序——IPO 设计与边界情况 · AB CSE1110 2.4.1 / ON ICS3U A2.1 [9 marks][9 分]

A student must write a program that reads a weight in kilograms and a height in metres from the user, computes the Body Mass Index (BMI = weight / height squared), and prints the BMI rounded to one decimal place.一名学生须编写一个程序:从用户读取体重(千克)和身高(米),计算体重指数(BMI = 体重 / 身高平方),并打印保留一位小数的 BMI。

(a) State the IPO (Input, Process, Output) for this program. List each input, the process formula, and the output.写出该程序的 IPO(输入、处理、输出)。列出每个输入、处理公式和输出。 [2]
(b) Write the complete Python program using the five-step pipeline. Use float(input(...)) for reading inputs and an f-string with :.1f for the output.用五步流程编写完整 Python 程序。使用 float(input(...)) 读取输入,用带 :.1f 的 f 字符串输出。 [3]
(c) Trace your program with weight = 70 and height = 1.75. Show the calculation and state the printed output.weight = 70height = 1.75 追踪你的程序。写出计算过程,并写出打印的输出。 [2]
(d) Identify two edge-case inputs that could cause your program to behave unexpectedly. For each, name the Python error (if any) that would occur.识别两种可能导致程序意外行为的边界情况输入。对每种情况,说明会发生的 Python 错误名称(如果有)。 [2]
Answers: (a) IPO listed  |  (b) complete program  |  (c) BMI = 22.9  |  (d) height=0 ZeroDivisionError; non-numeric ValueError答案:(a) IPO 如下  |  (b) 完整程序  |  (c) BMI = 22.9  |  (d) height=0 引发 ZeroDivisionError;非数值引发 ValueError

(a) A1+A1

  • Input: weight_kg (float, kilograms), height_m (float, metres)输入:weight_kg(float,千克),height_m(float,米)
  • Process: bmi = weight_kg / (height_m ** 2)处理:bmi = weight_kg / (height_m ** 2)
  • Output: BMI rounded to 1 decimal place (e.g., "BMI = 22.9")输出:保留 1 位小数的 BMI(如"BMI = 22.9")

(b) M1+A1+A1

weight_kg = float(input("Enter weight in kg: "))
height_m = float(input("Enter height in m: "))
bmi = weight_kg / (height_m ** 2)
print(f"BMI = {bmi:.1f}")

float(input(...)) handles decimal inputs. :.1f in the f-string formats to one decimal place.float(input(...)) 处理小数输入。f 字符串中的 :.1f 格式化为一位小数。

(c) M1+A1

Calculation: bmi = 70 / (1.75 ** 2) = 70 / 3.0625 = 22.857...计算:bmi = 70 / (1.75 ** 2) = 70 / 3.0625 = 22.857...

Printed output: BMI = 22.9 (rounded to 1 decimal place by :.1f).打印输出:BMI = 22.9(由 :.1f 四舍五入为 1 位小数)。

(d) A1+A1

  • height = 0: Division by zero raises ZeroDivisionError (cannot divide by 0 in Python).height = 0:除以零引发 ZeroDivisionError(Python 中不能除以 0)。
  • Non-numeric input (e.g., "abc"): float("abc") raises ValueError because "abc" cannot be converted to a float.非数值输入(如 "abc"):float("abc") 引发 ValueError,因为 "abc" 无法转换为浮点数。
Insight:洞察: The IPO model (Input - Process - Output) is the foundational design pattern for any program. Identifying it before writing code ensures you understand what data flows in, what transformation occurs, and what result leaves. Edge cases always come from the Process step: what values make the formula undefined? (Division by zero, square root of negative, log of non-positive.)IPO 模型(输入-处理-输出)是任何程序的基础设计模式。编写代码前先识别它,确保你理解什么数据流入、发生什么转换、输出什么结果。边界情况始终来自处理步骤:什么值使公式无定义?(除以零、负数开方、非正数取对数。)
PART III  ·  MODELING / APPLIED  ·  SOLUTIONS第三部分  ·  建模与应用  ·  答案Universal / multi-region applied · 25 marks通用/多地区应用题 · 共 25 分

Section C · Worked SolutionsC 部分 · 解析

Full solutions show complete traces, pseudocode, and Python programs. Mark breakdowns are shown per sub-part. An insight block connects each scenario to broader programming principles.完整解析包含完整追踪、伪代码和 Python 程序。分值明细按小问显示。洞察块将每个场景与更广泛的编程原理相连。

Q10 MEDIUM 🇺🇸 US 🇨🇦 ON AP CSP-feeder FRQAP CSP 衔接简答题 §2 + §3 + §4 Data types, I/O, and operators — applied数据类型、输入输出与运算符——应用 · ICS3U A1.1 / A2.1 / AB CSE1110 2.4.6 [8 marks][8 分]

A program reads the number of minutes a student studied and converts it to hours and leftover minutes. For example, 200 minutes = 3 hours and 20 minutes.一个程序读取学生学习的分钟数,并将其转换为小时数和剩余分钟数。例如,200 分钟 = 3 小时 20 分钟。

minutes = int(input("Enter total minutes studied: "))
hours = minutes // 60
leftover = minutes % 60
print(hours, "hours and", leftover, "minutes")
(a) Trace the program for the input 200. State the values of hours and leftover after lines 2 and 3 execute. Show your arithmetic.用输入 200 追踪程序。写出第 2、3 行执行后 hoursleftover 的值。写出算术过程。 [3]
(b) State the exact output of the program when the input is 200.写出输入为 200 时程序的精确输出。 [1]
(c) Why is the int() conversion on line 1 necessary? What error would occur without it when the user types 200?为什么第 1 行的 int() 转换是必要的?若没有它,用户输入 200 时会发生什么错误? [2]
(d) Write the pseudocode for this program using the standard block format (INPUT, SET, OUTPUT).使用标准块格式(INPUT、SET、OUTPUT)为该程序编写伪代码。 [2]
Answers: (a) hours=3, leftover=20  |  (b) "3 hours and 20 minutes"  |  (c) TypeError on // with str  |  (d) pseudocode below答案:(a) hours=3,leftover=20  |  (b) "3 hours and 20 minutes"  |  (c) str 上使用 // 引发 TypeError  |  (d) 伪代码如下

(a) M1+A1+A1

Line 2: hours = 200 // 60. 200 / 60 = 3.33..., so 200 // 60 = 3. hours = 3.第 2 行:hours = 200 // 60。200 / 60 = 3.33...,所以 200 // 60 = 3。hours = 3。

Line 3: leftover = 200 % 60. 200 = 60 * 3 + 20, so 200 % 60 = 20. leftover = 20.第 3 行:leftover = 200 % 60。200 = 60 * 3 + 20,所以 200 % 60 = 20。leftover = 20。

(b) A1

Exact output: 3 hours and 20 minutes精确输出:3 hours and 20 minutes

(c) A1+A1

Without int(), minutes is a str. The // operator cannot be applied to a string, so Python raises a TypeError: unsupported operand type(s) for //: 'str' and 'int'. The conversion to int is necessary because arithmetic operators require numeric types.若没有 int()minutesstr// 运算符不能用于字符串,Python 引发 TypeError:unsupported operand type(s) for //: 'str' and 'int'。转换为 int 是必要的,因为算术运算符需要数值类型。

(d) A1+A1

INPUT minutes
SET hours TO minutes // 60
SET leftover TO minutes % 60
OUTPUT hours, "hours and", leftover, "minutes"
Insight:洞察: The floor-division + modulo pair (// and %) is the canonical way to decompose a quantity into a larger unit and a remainder. Time (seconds to minutes/seconds), distance (cm to m/cm), money (cents to dollars/cents) all follow the same pattern. Recognising this pattern makes you a faster problem-solver across many domains.整除 + 取模组合(//%)是将数量分解为更大单位和余数的标准方法。时间(秒转分钟/秒)、距离(厘米转米/厘米)、金钱(分转元/分)都遵循相同模式。认识这一模式使你能在许多领域更快地解决问题。
Q11 MEDIUM 🇨🇦 ON 🇨🇦 BC ON Provincial-style安大略省考风格 §5 + §6 + §7 Type conversion, naming, and IPO design类型转换、命名与 IPO 设计 · ICS3U A1.3 / A2.1 / AB CSE1110 2.4.1 [8 marks][8 分]

A student is writing a program to compute an HST-inclusive price. Ontario HST rate is 13%. The program should read a pre-tax price, compute the tax, and display the final price with two decimal places. The student's first draft is shown below.一名学生正在编写一个程序,计算含 HST 的价格。安大略省 HST 税率为 13%。程序应读取含税前价格,计算税额,并以两位小数显示最终价格。学生的初稿如下。

# Draft 1
p = input("Enter price: ")
t = p * 0.13
f = p + t
print("Final:", f)
(a) Identify two errors in Draft 1 and explain each in one sentence.识别初稿 1 中的两处错误,每处用一句话解释。 [2]
(b) Rewrite the program using descriptive names and a named constant for the tax rate. Use an f-string with :.2f for the output line. The corrected version should handle decimal inputs correctly.用描述性名称和税率具名常量重写程序。输出行使用带 :.2f 的 f 字符串。更正版应正确处理小数输入。 [4]
(c) Trace your corrected program with an input of 100.00. State the values of each variable and the printed output.用输入 100.00 追踪你的更正程序。写出每个变量的值以及打印的输出。 [2]
Answers: (a) missing float() + cryptic names  |  (b) corrected program  |  (c) tax=13.0, final=113.0, "Final: 113.00"答案:(a) 缺少 float() 转换 + 命名不清  |  (b) 更正程序  |  (c) tax=13.0,final=113.0,"Final: 113.00"

(a) A1+A1

  • Error 1 (type): p = input(...) returns a str, so p * 0.13 raises a TypeError (cannot multiply str by float). Fix: wrap with float().错误 1(类型):p = input(...) 返回 str,所以 p * 0.13 引发 TypeError(不能将 str 与 float 相乘)。修复:包裹在 float() 中。
  • Error 2 (naming): Single-letter variable names p, t, f are not descriptive; they violate naming conventions and reduce readability/maintainability.错误 2(命名):单字母变量名 ptf 不具描述性;违反命名规范,降低可读性/可维护性。

(b) M1+A1+A1+A1

TAX_RATE = 0.13
price_before_tax = float(input("Enter price: "))
tax_amount = price_before_tax * TAX_RATE
final_price = price_before_tax + tax_amount
print(f"Final: {final_price:.2f}")

(c) A1+A1

Trace for input 100.00:输入 100.00 的追踪:

  • TAX_RATE = 0.13
  • price_before_tax = 100.0
  • tax_amount = 100.0 * 0.13 = 13.0
  • final_price = 100.0 + 13.0 = 113.0
  • Printed output: Final: 113.00打印输出:Final: 113.00
Insight:洞察: This question combines three quality dimensions of beginner code: correct types (float not str), meaningful names (not single letters), and formatted output (:.2f for currency). Professional code achieves all three simultaneously. The named constant TAX_RATE also signals intent to future readers of the code.此题综合了初学者代码的三个质量维度:正确类型(float 而非 str)、有意义的命名(非单字母)、格式化输出(货币用 :.2f)。专业代码同时实现三者。具名常量 TAX_RATE 也向代码未来的读者传达了意图。
Q12 HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC AP CSP-feeder FRQAP CSP 衔接简答题 All sections · Full program design and debugging全节综合 · 完整程序设计与调试 · AP CSP AAP-1 / AB CSE1110 2.4.1-2.4.7 [9 marks][9 分]

A student is writing a program that asks the user for their first name and birth year, then prints a personalised message with their age. Today's year is 2026. The student's buggy version is shown below.一名学生正在编写一个程序,询问用户的名字和出生年份,然后打印带有年龄的个性化消息。今年是 2026 年。学生的有错误版本如下。

CURRENT_YEAR = 2026
name = input("Enter your first name: ")
birth_year = input("Enter your birth year: ")
age = CURRENT_YEAR - birth_year
message = "Hello " + name + "! You are " + age + " years old."
print(message)
(a) Identify the two errors in this program. For each error, name the Python exception it would raise and explain why.识别该程序中的两处错误。对每处错误,说明它会引发的 Python 异常名称及原因。 [4]
(b) Write the corrected complete program. The naming convention for the constant should be preserved.写出更正后的完整程序。应保留常量的命名规范。 [3]
(c) Trace your corrected program for name "Li" and birth year 2010. State the exact printed output.用名字 "Li"、出生年份 2010 追踪你的更正程序。写出精确的打印输出。 [2]
Answers: (a) TypeError on int-str subtraction + TypeError on str+int concatenation  |  (b) corrected program  |  (c) "Hello Li! You are 16 years old."答案:(a) int-str 相减的 TypeError + str+int 拼接的 TypeError  |  (b) 更正程序  |  (c) "Hello Li! You are 16 years old."

(a) M1+A1+M1+A1

  • Error 1 (line 4): birth_year = input(...) returns a str. The expression CURRENT_YEAR - birth_year subtracts a string from an integer, raising a TypeError: unsupported operand type(s) for -: 'int' and 'str'.错误 1(第 4 行):birth_year = input(...) 返回 str。表达式 CURRENT_YEAR - birth_year 从整数中减去字符串,引发 TypeError:unsupported operand type(s) for -: 'int' and 'str'。
  • Error 2 (line 5): After fixing Error 1, age is an int. The expression "Hello " + name + "! You are " + age + " years old." attempts string + int concatenation, raising a TypeError: can only concatenate str (not "int") to str.错误 2(第 5 行):修复错误 1 后,ageint。表达式 "Hello " + name + "! You are " + age + " years old." 尝试字符串 + 整数拼接,引发 TypeError:can only concatenate str (not "int") to str。

(b) M1+A1+A1

CURRENT_YEAR = 2026
name = input("Enter your first name: ")
birth_year = int(input("Enter your birth year: "))
age = CURRENT_YEAR - birth_year
message = f"Hello {name}! You are {age} years old."
print(message)

Fixes: int(input(...)) for birth_year; f-string avoids str+int TypeError.修复:对 birth_year 使用 int(input(...));f 字符串避免了 str+int 的 TypeError。

(c) M1+A1

  • CURRENT_YEAR = 2026
  • name = "Li"
  • birth_year = 2010
  • age = 2026 - 2010 = 16
  • Printed output: Hello Li! You are 16 years old.打印输出:Hello Li! You are 16 years old.
Insight:洞察: This question tests systematic debugging: there are two independent errors, each in a different expression. Beginners often fix only the first error they see. Professional debugging traces each line and checks whether every operation is type-compatible. F-strings are the modern, idiomatic Python way to embed variables in strings without explicit type conversion.此题测试系统性调试:有两处独立错误,分别位于不同表达式中。初学者常常只修复他们看到的第一处错误。专业调试逐行追踪,检查每个操作是否类型兼容。F 字符串是现代、惯用的 Python 方式,无需显式类型转换即可将变量嵌入字符串。