Full Worked Solutions · AP CSP-Feeder · US / ON / BC / AB Styles完整解析答案集 · AP CSP 衔接 · 美 / 安 / 卑 / 阿省风格
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 答案分)以及将结论与更广泛原理联系的洞察块。分值分配与配套练习题一致。
After the following three lines execute, what is the value of y?以下三行执行后,y 的值是什么?
x = 4
y = x + 3
x = 10
101374When line 2 executes, x holds 4, so Python evaluates 4 + 3 = 7 and stores that value in y.第 2 行执行时,x 为 4,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
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 了。这是赋值与别名的根本区别。Which of the following is the correct data type for the value "3.14" (with quotes) in Python?以下哪项是 Python 中 "3.14"(带引号)的正确数据类型?
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
str. This distinction matters deeply when doing arithmetic: "3.14" + 1 raises a TypeError.数据类型由源代码中的定界符决定,而非值的外观。引号始终意味着 str。这一区别在做算术时至关重要:"3.14" + 1 会引发 TypeError。A student writes the following program. The user types 5 at the prompt.一名学生编写了以下程序。用户在提示符处输入 5。
n = input("Enter a number: ")
result = n * 2
print(result)
n after line 1 executes. Explain why.写出第 1 行执行后 n 的数据类型。解释原因。 [2]result holds after line 2 executes. State its data type too.写出第 2 行执行后 result 保存的精确值。同时写出其数据类型。 [2]result to be 10 (integer). Write the corrected line 1 that fixes the bug.学生希望 result 为 10(整数)。写出修正后的第 1 行以修复该错误。 [2]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。
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"。
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。
print()
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 获得的是数字,而不显式转换。Given a = 17 and b = 5, evaluate each expression below.给定 a = 17,b = 5,计算以下每个表达式。
a // b and its data type.写出 a // b 的值及其数据类型。 [2]a % b and explain what it represents.写出 a % b 的值,并解释它代表什么。 [2]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]17 // 5 = 3. Floor division discards the remainder. Data type: int (integer // integer returns integer).17 // 5 = 3。整除运算舍弃余数。数据类型:int(整数整除整数返回整数)。
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 份后剩余的量。
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 = True。b == 5 计算结果为 5 == 5 = True。True and True = True。整个表达式为 True。
// 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)、循环索引等。掌握它们可以在许多整数场景中避免使用除法。For each line of Python below, state the result and its data type. If the line raises an error, name the error.对以下每行 Python,写出结果及其数据类型。若该行引发错误,请说明错误名称。
int(7.9) [2]str(42) + " points" [2]int("3.9") [2]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。
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。
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。
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。切勿在未验证的情况下假设字符串是数值。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(答案分)。满分须写出追踪步骤、数据类型及推理过程,而非仅给出最终答案。
Answer each naming question below.回答以下每道命名问题。
snake_case convention for a variable storing a student's total score?哪个变量名遵循 Python 的 snake_case 规范,用于存储学生的总分? [1]
TotalScoretotal_scoreTOTAL_SCOREts0.13 should not change during the program. Write the correctly named Python line that declares it as a constant.税率值 0.13 在程序运行中不应改变。写出将其声明为常量的正确命名 Python 语句。 [1]TAX_RATE = 0.13 instead of the literal 0.13 throughout the code is better practice.用两句话解释为什么在代码中使用 TAX_RATE = 0.13 而不是字面值 0.13 是更好的实践。 [2](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) 缩写过短。
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 不强制不可变性,但命名规范向其他程序员表明该值不应被修改。
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。
PascalCase (also called UpperCamelCase): each word starts with a capital letter, no underscores. Example: StudentRecord, BankAccount.PascalCase(也称大驼峰命名法):每个单词首字母大写,无下划线。示例:StudentRecord、BankAccount。
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, b, and temp after that line executes.逐行追踪程序。对第 3-5 行,写出该行执行后 a、b、temp 的值。 [3]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]After lines 1-2: a = 10, b = 20.第 1-2 行后:a = 10, b = 20。
temp = a -- a = 10, b = 20, temp = 10第 3 行:temp = a -- a = 10, b = 20, temp = 10a = b -- a = 20, b = 20, temp = 10第 4 行:a = b -- a = 20, b = 20, temp = 10b = temp -- a = 20, b = 10, temp = 10第 5 行:b = temp -- a = 20, b = 10, temp = 10Output: 20 10. Python's print(a, b) prints values separated by a space.输出:20 10。Python 的 print(a, b) 用空格分隔打印各值。
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.若没有 temp:a = b 用 b 的值 (20) 覆盖了 a(值 10)。然后 b = a 将 20 复制回 b。两个变量最终都保存 20 -- a 的原始值 (10) 永久丢失。temp 在 a 被覆盖之前保存了其原始值。
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),再同时解包到 a 和 b 中。无需临时变量。
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 风格的优雅写法,但理解临时变量版本可学到在每种语言中都通用的可迁移模式。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)
Final score: 95 when the user enters 85.写出更正后的程序 A。当用户输入 85 时,更正版应输出 Final score: 95。 [2]str() concatenation or an f-string.写出更正后的程序 B 中构建消息字符串的那一行。可以使用 str() 拼接或 f 字符串。 [2]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 引发 TypeError。score = input(...) 返回 str。表达式 score + 10 尝试将字符串与整数相加,Python 不允许此操作。错误信息:can only concatenate str (not "int") to str。
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。
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 引发 TypeError。price 是 float(已正确转换)。表达式 "Total is " + price 尝试拼接字符串与浮点数,Python 不允许。修复方法是拼接前将 price 转换为字符串。
Using str() concatenation:使用 str() 拼接:
message = "Total is " + str(price)
Or using an f-string:或使用 f 字符串:
message = f"Total is {price}"
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 字符串通过内部处理转换完全避免了这一问题。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。
float(input(...)) for reading inputs and an f-string with :.1f for the output.用五步流程编写完整 Python 程序。使用 float(input(...)) 读取输入,用带 :.1f 的 f 字符串输出。 [3]weight = 70 and height = 1.75. Show the calculation and state the printed output.用 weight = 70、height = 1.75 追踪你的程序。写出计算过程,并写出打印的输出。 [2]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 格式化为一位小数。
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 位小数)。
ZeroDivisionError (cannot divide by 0 in Python).height = 0:除以零引发 ZeroDivisionError(Python 中不能除以 0)。float("abc") raises ValueError because "abc" cannot be converted to a float.非数值输入(如 "abc"):float("abc") 引发 ValueError,因为 "abc" 无法转换为浮点数。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 程序。分值明细按小问显示。洞察块将每个场景与更广泛的编程原理相连。
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")
200. State the values of hours and leftover after lines 2 and 3 execute. Show your arithmetic.用输入 200 追踪程序。写出第 2、3 行执行后 hours 和 leftover 的值。写出算术过程。 [3]200.写出输入为 200 时程序的精确输出。 [1]int() conversion on line 1 necessary? What error would occur without it when the user types 200?为什么第 1 行的 int() 转换是必要的?若没有它,用户输入 200 时会发生什么错误? [2]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。
Exact output: 3 hours and 20 minutes精确输出:3 hours and 20 minutes
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(),minutes 是 str。// 运算符不能用于字符串,Python 引发 TypeError:unsupported operand type(s) for //: 'str' and 'int'。转换为 int 是必要的,因为算术运算符需要数值类型。
INPUT minutes
SET hours TO minutes // 60
SET leftover TO minutes % 60
OUTPUT hours, "hours and", leftover, "minutes"
// 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.整除 + 取模组合(// 和 %)是将数量分解为更大单位和余数的标准方法。时间(秒转分钟/秒)、距离(厘米转米/厘米)、金钱(分转元/分)都遵循相同模式。认识这一模式使你能在许多领域更快地解决问题。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)
:.2f for the output line. The corrected version should handle decimal inputs correctly.用描述性名称和税率具名常量重写程序。输出行使用带 :.2f 的 f 字符串。更正版应正确处理小数输入。 [4]100.00. State the values of each variable and the printed output.用输入 100.00 追踪你的更正程序。写出每个变量的值以及打印的输出。 [2]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() 中。p, t, f are not descriptive; they violate naming conventions and reduce readability/maintainability.错误 2(命名):单字母变量名 p、t、f 不具描述性;违反命名规范,降低可读性/可维护性。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}")
Trace for input 100.00:输入 100.00 的追踪:
TAX_RATE = 0.13price_before_tax = 100.0tax_amount = 100.0 * 0.13 = 13.0final_price = 100.0 + 13.0 = 113.0Final: 113.00打印输出:Final: 113.00float 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 也向代码未来的读者传达了意图。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)
"Li" and birth year 2010. State the exact printed output.用名字 "Li"、出生年份 2010 追踪你的更正程序。写出精确的打印输出。 [2]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'。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 后,age 是 int。表达式 "Hello " + name + "! You are " + age + " years old." 尝试字符串 + 整数拼接,引发 TypeError:can only concatenate str (not "int") to str。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。
CURRENT_YEAR = 2026name = "Li"birth_year = 2010age = 2026 - 2010 = 16Hello Li! You are 16 years old.打印输出:Hello Li! You are 16 years old.