Programming Fundamentals编程基础
Every program is built from a handful of core ideas: storing data in variables, choosing the right data type, reading input from a user and writing output back, combining values with operators, converting between types, and organising code with constants and clear names. This guide builds all seven fundamentals from scratch, with pseudocode and Python side-by-side throughout, so you leave each section able to write, read, and explain real working code. By the end you will have written and run your first complete program, and understood exactly what every line does.每个程序都建立在少数核心概念上:将数据存储在变量(variable,变量)中、选择正确的数据类型(data type,数据类型)、从用户读取输入(input,输入)并写出输出(output,输出)、用运算符(operator,运算符)组合值、在类型之间转换(type conversion,类型转换),以及用常量(constant,常量)和清晰命名组织代码。本指南从零建立全部七个基础,伪代码与 Python 全程并排,让你在每节结束后都能编写、阅读并解释真正可运行的代码。学完后,你将编写并运行第一个完整程序,并准确理解每一行的含义。
Variables and Assignment变量与赋值
- Trace a sequence of assignment statements and state the value of every variable after each line.
- Explain why
x = x + 1is a valid statement even though no number equals itself plus one. - Distinguish assignment (
=) from the equality test (==). - Swap two variables with a temporary variable and with tuple unpacking.
- 追踪一系列赋值语句,并说出每一行之后每个变量的值。
- 解释为什么
x = x + 1是合法语句,尽管没有数等于它自己加一。 - 区分赋值(
=)与等式测试(==)。 - 用临时变量和元组解包两种方式交换两个变量。
- Variable变量: a named storage location in memory that holds a value. The name is chosen by the programmer. AP CSP AAP-1.A: "Represent a value with a variable.":内存中保存值的具名存储位置。名称由程序员选择。AP CSP AAP-1.A:"用变量表示一个值。"
- Assignment赋值: stores a value in a variable.
x = 5puts 5 into x. AP CSP AAP-1.B: "Determine the value of a variable as a result of an assignment." ON ICS3U A1.3: "use assignment statements correctly.":将值存储在变量中。x = 5将 5 放入 x。AP CSP AAP-1.B:"确定赋值后变量的值。"ON ICS3U A1.3:"正确使用赋值语句。" - Assignment ≠ equality test赋值 ≠ 等式测试:
x = 5(single=) writes 5 to x.x == 5(double==) checks if x equals 5. Confusing them is the single most common beginner error.:x = 5(单个=)将 5 写入 x。x == 5(双==)检查 x 是否等于 5。混淆两者是最常见的初学者错误。
x = x + 1 is valid: read x, add 1, write back. AB CSE1110 outcome 2.4.4: "use appropriate variables and constants to hold data."核心思路:每次赋值后,变量恰好保存一个值。右侧首先使用所有变量的当前状态求值,然后将结果存储到左侧。所以 x = x + 1 是合法的:读取 x,加 1,写回。AB CSE1110 结果 2.4.4:"使用适当的变量和常量保存数据。"
Worked Example 1: Swapping two variables例题 1:交换两个变量
Problem: given a = 10 and b = 20, swap their values so that after the operation a == 20 and b == 10. Write pseudocode and Python.问题:给定 a = 10 和 b = 20,交换它们的值,使操作后 a == 20,b == 10。写出伪代码和 Python。
Pseudocode (using a temporary variable).伪代码(使用临时变量)。
SET a TO 10
SET b TO 20
SET temp TO a -- save a's value
SET a TO b -- a now holds 20
SET b TO temp -- b now holds 10
OUTPUT a, b -- prints: 20 10
Without temp, the first assignment SET a TO b would overwrite a's original value before b could capture it.若没有 temp,第一条赋值 SET a TO b 会在 b 捕获 a 的原始值之前将其覆盖。
Python (two ways).Python(两种方式)。
# Classic temp variable
a = 10
b = 20
temp = a
a = b
b = temp
print(a, b) # 20 10
# Python shortcut (tuple unpacking)
a, b = b, a
print(a, b) # 20 10
The tuple-unpacking shortcut evaluates both sides before any assignment, so no temp is needed. Both produce identical results.元组解包方式在任何赋值之前就对两侧求值,因此不需要临时变量。两种方式产生相同结果。
Worked Example 2: Tracing a sequence of assignments例题 2:追踪一系列赋值
Problem: trace the five-line program below. Record the value of every variable after each line in a table, then state the final values of a, b and c.问题:追踪下面的五行程序。用表格记录每一行之后每个变量的值,然后写出 a、b 和 c 的最终值。
Program.程序。
a = 4
b = a * 2
a = a + b
b = b - a
c = a * b
print(a, b, c) # 12 -4 -48
Line 1 stores 4 in a. Line 2 evaluates a * 2 with the current a (4), so b becomes 8. Line 3 evaluates the right-hand side a + b first, using a = 4 and b = 8, and only then writes 12 into a; the old value 4 is gone. Line 4 must use the new a: 8 - 12 = -4. Line 5 gives 12 * (-4) = -48. Figure 1 shows the whole trace.第 1 行将 4 存入 a。第 2 行用当前的 a(4)计算 a * 2,所以 b 变为 8。第 3 行先计算右侧 a + b,使用 a = 4 和 b = 8,之后才把 12 写入 a;旧值 4 就消失了。第 4 行必须使用新的 a:8 - 12 = -4。第 5 行得到 12 * (-4) = -48。图 1 展示了完整的追踪过程。
Final answer: a = 12, b = -4, c = -48, and the program prints 12 -4 -48. Common error: using the old a = 4 on line 4, which gives b = 4 and a wrong c of 16.最终答案:a = 12,b = -4,c = -48,程序打印 12 -4 -48。常见错误:在第 4 行使用旧的 a = 4,得到 b = 4,并使 c 错误地变成 16。
Command words: "trace" asks for the value of each variable after each line (a table), "state" asks for the final values only, and "explain" needs a reason. Common errors: using the old value of the variable being assigned when reading the right-hand side, and believing that a variable updates itself when a variable it was computed from changes later.
指令词:"追踪"要求列出每一行之后每个变量的值(表格),"写出"只要求最终值,"解释"需要给出理由。常见错误:读取右侧时使用了被赋值变量的旧值,以及误以为当计算它所用的变量之后改变时,它会自动更新。
After a = 2, b = a + 3, a = b * 2, b = a - b run in order, what are a and b?依次运行 a = 2、b = a + 3、a = b * 2、b = a - b 后,a 和 b 各是多少?
Trace: a = 2; b = 2 + 3 = 5; a = 5 * 2 = 10; b = 10 - 5 = 5. So a = 10 and b = 5.
追踪:a = 2;b = 2 + 3 = 5;a = 5 * 2 = 10;b = 10 - 5 = 5。所以 a = 10,b = 5。
A student swaps a = 3 and b = 9 with a = b then b = a. What do the variables hold, and what is the fix?一名学生用 a = b 再 b = a 来交换 a = 3 和 b = 9。两个变量各保存什么?如何修正?
Both hold 9. After a = b the original 3 is overwritten, so b = a copies 9. Fix: save the value first with temp = a, or write a, b = b, a.
两者都保存 9。a = b 之后原来的 3 已被覆盖,所以 b = a 复制的是 9。修正:先用 temp = a 保存,或写 a, b = b, a。
A classmate says x = x + 1 must be an error because x cannot equal x + 1. Respond.同学说 x = x + 1 一定是错误,因为 x 不可能等于 x + 1。请回应。
The single = is assignment, not an equation. It reads the current x, adds 1 and stores the result back in x. The test x == x + 1 is a different statement and is always False.
单个 = 是赋值,不是等式。它读取 x 的当前值,加 1,再把结果存回 x。测试 x == x + 1 是另一回事,结果始终为 False。
y?x = 3y = x + 4x = 10这几行运行后,y 的值是什么?x = 3y = x + 4x = 10score by 10?哪行代码能正确地将 score 的值增加 10?score = score + 10 reads the current value of score, adds 10, then writes the result back to score. Single = is assignment. Double == is a comparison that returns True/False but stores nothing.score = score + 10 读取 score 当前值,加 10,然后将结果写回 score。单个 = 是赋值。双 == 是返回 True/False 但不存储任何内容的比较。= stores a value. The left side must be a variable name. score + 10 = score and 10 + score (no assignment) are invalid for this purpose.只有单个 = 才能存储值。左侧必须是变量名。score + 10 = score 和 10 + score(无赋值)不适用于此目的。Going deeper: variable names and memory model深入:变量名与内存模型
In Python, a variable name is a label that points to an object in memory; the object itself carries the type. When you write x = 5, Python creates an integer object with value 5 and makes the name x point to it. When you write x = "hello" next, x now points to a string object; the integer 5 object is unchanged (and eventually garbage-collected if nothing else references it). This is different from statically-typed languages like Java or C where a variable has a fixed type declared at creation. Understanding this model explains why Python variables can be reassigned to a different type, and why is tests identity (same object) while == tests equality (same value). AP CSP AAP-1.A/1.B treats variables as simple value containers; the Python object model is a going-deeper layer.在 Python 中,变量名是指向内存中对象的标签;对象本身携带类型。当你写 x = 5 时,Python 创建一个值为 5 的整数对象,并让名称 x 指向它。当你接着写 x = "hello" 时,x 现在指向一个字符串对象;整数 5 对象不变(如果没有其他引用,最终会被垃圾回收)。这与 Java 或 C 等静态类型语言不同,在那些语言中变量在创建时声明了固定类型。理解这个模型解释了为什么 Python 变量可以重新赋值为不同类型,以及为什么 is 测试同一性(同一对象)而 == 测试相等性(相同值)。AP CSP AAP-1.A/1.B 将变量视为简单的值容器,Python 对象模型是深入层次的内容。
Data Types: int, float, string, boolean数据类型:整数、浮点数、字符串、布尔
- Name the four basic types
int,float,strandbooland give a value of each. - Predict the type and value of an expression that mixes ints, floats and strings.
- Choose a suitable type for a count, a measurement, an identifier and a yes/no flag, and justify the choice.
- Explain why
"42"and42behave differently.
- 说出四种基本类型
int、float、str和bool,并各举一个值。 - 预测混合整数、浮点数和字符串的表达式的类型与值。
- 为计数、测量值、标识符和是/否标志选择合适的类型,并说明理由。
- 解释为什么
"42"和42的行为不同。
- intint(整数): whole numbers, positive or negative. Examples:
42,-7,0. Use for counts, indices, ages.:正负整数。例:42、-7、0。用于计数、索引、年龄。 - floatfloat(浮点数): numbers with a decimal point. Examples:
3.14,-0.5,2.0. Use for measurements, prices, scientific values.:含小数点的数。例:3.14、-0.5、2.0。用于测量值、价格、科学值。 - strstr(字符串): a sequence of characters enclosed in quotes. Examples:
"hello","42",""(empty string). Use for text, names, messages.:用引号括起来的字符序列。例:"hello"、"42"、""(空字符串)。用于文本、姓名、消息。 - boolbool(布尔): exactly two values:
TrueorFalse. Use for conditions, flags, on/off states. ON ICS3U A1.1: "use constants and variables, including integers, floating points, strings, and Boolean values, correctly.":只有两个值:True(真)或False(假)。用于条件、标志、开/关状态。ON ICS3U A1.1:"正确使用常量和变量,包括整数、浮点数、字符串和布尔值。"
"42" (string) and 42 (integer) are different objects. You cannot add a string and a number: "score" + 5 raises a TypeError. Always check the type before combining values. AB CSE1110 outcome 2.4.3: "use appropriate data types such as integers, real numbers, characters and strings."关键陷阱:"42"(字符串)和 42(整数)是不同的对象。不能把字符串和数字相加:"score" + 5 会引发 TypeError。在组合值之前始终检查类型。AB CSE1110 结果 2.4.3:"使用适当的数据类型,如整数、实数、字符和字符串。"
Worked Example 3: Declaring and inspecting types例题 3:声明并检查类型
Declare one variable of each type and use type() to confirm.声明每种类型的一个变量,并用 type() 确认。
age = 17 # int
gpa = 3.85 # float
name = "Alex" # str
passed = True # bool
print(type(age)) # <class 'int'>
print(type(gpa)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(passed)) # <class 'bool'>
Python infers the type from the literal value written on the right-hand side: integer literal → int, decimal literal → float, quoted text → str, True/False → bool. No explicit type declaration is needed in Python (unlike Java's int age = 17;).Python 从右侧写的字面值推断类型:整数字面值 → int,十进制字面值 → float,引号文本 → str,True/False → bool。Python 不需要显式类型声明(不同于 Java 的 int age = 17;)。
Worked Example 4: Choosing types and predicting expression types例题 4:选择类型并预测表达式类型
Problem: a school record must hold the number of siblings, a student's average, a postal code and whether fees are paid. Choose a type for each and justify it. Then predict what each of eight expressions prints.问题:学校记录需要保存兄弟姐妹数量、学生平均分、邮政编码以及是否已缴费。为每项选择类型并说明理由。然后预测八个表达式各自打印什么。
Part 1: choose the type.第 1 部分:选择类型。
siblings = 2 # int: a count of whole things
average = 87.5 # float: a measurement with a fraction
postal_code = "V6B 1A1" # str: letters, digits and a space
fees_paid = True # bool: exactly two states
print(int("007")) # 7 (leading zeros are lost)
A count of siblings is a whole number, so int. An average has a fractional part, so float. A postal code is an identifier, not a quantity: nobody adds two postal codes, and a code such as 007 would lose its zeros as a number, so it is a str. Fees paid has two states, so bool.兄弟姐妹数量是整数,所以用 int。平均分带小数部分,所以用 float。邮政编码是标识符而不是数量:没人会把两个邮政编码相加,而且像 007 这样的编码作为数字会丢掉前导零,所以用 str。是否缴费只有两种状态,所以用 bool。
Part 2: predict the expressions.第 2 部分:预测表达式。
print(type(7 / 2)) # <class 'float'>
print(type(7 // 2)) # <class 'int'>
print(7.0 // 2) # 3.0
print(3 + 2.0) # 5.0
print("5" + "5") # 55
print(type(5 > 3)) # <class 'bool'>
print(True + True) # 2
print("3" * 3) # 333
The operator / always gives a float, even for 7 / 2. The operator // on two ints gives an int, but as soon as one operand is a float the result is a float (3.0). Mixing an int and a float gives a float. On strings, + joins text and * with an int repeats it. A comparison gives a bool, and True counts as 1 in arithmetic. Common error: expecting "5" + "5" to be 10.运算符 / 总是给出浮点数,即使是 7 / 2。对两个整数使用 // 得到整数,但只要有一个操作数是浮点数,结果就是浮点数(3.0)。整数与浮点数混合得到浮点数。对字符串,+ 连接文本,* 与整数相乘表示重复。比较运算得到 bool,而 True 在算术中算作 1。常见错误:以为 "5" + "5" 等于 10。
Command words: "state the type" wants the type name (int, float, str or bool), "predict" wants the printed value and its type, and "justify" wants a reason tied to how the data is used. Common errors: calling "3.14" (with quotes) a float, and storing identifiers such as postal codes or student numbers as numbers.
指令词:"写出类型"要求写出类型名称(int、float、str 或 bool),"预测"要求写出打印的值及其类型,"说明理由"要求给出与数据用途相关的理由。常见错误:把带引号的 "3.14" 称为浮点数,以及把邮政编码、学号等标识符存成数字。
State the type and value of 10 / 5, 10 // 5, 2 * 3.0 and "2" * 3.写出 10 / 5、10 // 5、2 * 3.0 和 "2" * 3 的类型和值。
10 / 5 is the float 2.0; 10 // 5 is the int 2; 2 * 3.0 is the float 6.0; "2" * 3 is the str "222".
10 / 5 是浮点数 2.0;10 // 5 是整数 2;2 * 3.0 是浮点数 6.0;"2" * 3 是字符串 "222"。
Which type should store a student number such as 004512, and why?像 004512 这样的学号应该用哪种类型存储?为什么?
A str. A student number is an identifier that is never used in arithmetic, and as an int it would become 4512 and lose its leading zeros.
str。学号是不参与算术运算的标识符,存成整数会变成 4512 并丢掉前导零。
Is "False" (with quotes) a bool? What does bool("False") give?带引号的 "False" 是 bool 吗?bool("False") 的结果是什么?
No, it is a str, because of the quotes. A non-empty string converts to True, so bool("False") is True.
不是,加了引号它是字符串。非空字符串转换后为 True,所以 bool("False") 是 True。
"3.14" (with quotes) in Python?在 Python 中,"3.14"(带引号)的数据类型是什么?"3.14" is a string containing the characters 3, ., 1, 4, not the floating-point number 3.14. You cannot do arithmetic directly on it.引号总是创建字符串,无论里面是什么。"3.14" 是包含字符 3、.、1、4 的字符串,而不是浮点数 3.14。不能直接对它进行算术运算。Going deeper: static vs dynamic typing and Java comparison深入:静态与动态类型及 Java 对比
Python is dynamically typed: the type is attached to the object, not the variable name, and can change at runtime. Java is statically typed: the type is declared with the variable name and cannot change. In Java: int age = 17; locks age to integers forever; writing age = "seventeen" is a compile-time error. In Python: age = 17 then age = "seventeen" is legal (though bad practice). AP CSA (Java) requires static type declarations from Unit 1; this guide's Python examples carry over directly because the underlying type concepts are the same; only the declaration syntax differs. ON ICS4U A1.4 adds the idea of finite representation limits: an int in Java holds at most 2,147,483,647 (2³¹ − 1); exceeding it causes integer overflow, a silent logic error. Python integers have no size limit (arbitrary precision), which is why overflow is not a Python beginner concern.Python 是动态类型:类型附加在对象上,而不是变量名上,可以在运行时改变。Java 是静态类型:类型随变量名声明,不可更改。Java 中:int age = 17; 永久将 age 锁定为整数;写 age = "seventeen" 是编译时错误。Python 中:age = 17 后 age = "seventeen" 是合法的(尽管是不良实践)。AP CSA(Java)从第 1 单元就要求静态类型声明;本指南的 Python 示例可直接迁移,因为底层类型概念相同,只是声明语法不同。ON ICS4U A1.4 增加了有限表示局限的概念:Java 中的 int 最多保存 2,147,483,647(2³¹ − 1);超出则导致整数溢出,一种无声的逻辑错误。Python 整数没有大小限制(任意精度),这就是为什么溢出不是 Python 初学者需要关心的问题。
Input and Output输入与输出
- Read numeric input with
int(input())orfloat(input()), choosing the converter from the data. - Produce output with
print(commas,sep,end) and with f-strings such as{average:.1f}. - Predict the output of a short program for given inputs, including what
input()returns before conversion. - Name the error raised when typed text cannot be converted.
- 用
int(input())或float(input())读取数值输入,并根据数据选择转换函数。 - 用
print(逗号、sep、end)和{average:.1f}这样的 f 字符串生成输出。 - 预测短程序在给定输入下的输出,包括
input()在转换前返回什么。 - 说出输入文本无法转换时引发的错误名称。
input(prompt)input(提示): reads a line of text typed by the user and returns it as a string, always. If you need a number, convert it immediately:age = int(input("Age: ")). ON ICS3U A2.1: "write programs that incorporate user input, processing, and screen output.":读取用户输入的一行文本,始终以字符串返回。如果需要数字,立即转换:age = int(input("年龄:"))。ON ICS3U A2.1:"编写包含用户输入、处理和屏幕输出的程序。"print(value, ...)print(值, ...): sends output to the screen. Can print multiple values separated by commas:print("Name:", name, "Age:", age). AB CSE1110 outcome 2.4.7: "use output commands … to display processed data.":将输出发送到屏幕。可以用逗号分隔打印多个值:print("姓名:", name, "年龄:", age)。AB CSE1110 结果 2.4.7:"使用输出命令……显示已处理数据。"
input() ALWAYS returns a string. Forgetting to convert is the most common beginner I/O bug: x = input("Enter number: ") then x + 1 raises a TypeError because you are trying to add a string and an int. AB CSE1110 outcome 2.4.5: "use literals and input commands … to provide data for processing."关键:input() 始终返回字符串。忘记转换是最常见的初学者 I/O 错误:x = input("输入数字:") 然后 x + 1 会引发 TypeError,因为你在尝试将字符串和整数相加。AB CSE1110 结果 2.4.5:"使用字面量和输入命令……提供待处理数据。"
Worked Example 5: Area of a rectangle例题 5:矩形面积
Read width and height from the user and print the area.从用户读取宽度和高度,打印面积。
Pseudocode.伪代码。
INPUT width
INPUT height
SET area TO width * height
OUTPUT area
Python.Python。
width = float(input("Enter width: "))
height = float(input("Enter height: "))
area = width * height
print("Area =", area)
We use float() so the program handles decimal dimensions (e.g., 3.5 metres). If we used int(), entering 3.5 would raise a ValueError. Always choose the conversion that matches what the user might realistically type.使用 float() 是为了让程序处理小数尺寸(如 3.5 米)。如果使用 int(),输入 3.5 会引发 ValueError。始终选择与用户实际可能输入相匹配的转换。
Worked Example 6: Average of three scores with formatted output例题 6:三个分数的平均值与格式化输出
Problem: read three whole-number test scores, then print their total and their average to one decimal place. Trace the run for the inputs 78, 91 and 84.问题:读取三个整数测试分数,然后打印它们的总和以及保留一位小数的平均值。追踪输入 78、91 和 84 的运行过程。
Pseudocode.伪代码。
INPUT s1, s2, s3
SET total TO s1 + s2 + s3
SET average TO total / 3
OUTPUT total
OUTPUT average (1 decimal)
Python.Python。
s1 = int(input("Score 1: "))
s2 = int(input("Score 2: "))
s3 = int(input("Score 3: "))
total = s1 + s2 + s3
average = total / 3
print("Total:", total)
print(f"Average: {average:.1f}")
Each score is a whole number, so int() is the right converter. A sample run (the user types the numbers after each prompt) looks like this:每个分数都是整数,所以应使用 int() 转换。一次示例运行如下(用户在每个提示后输入数字):
Score 1: 78
Score 2: 91
Score 3: 84
Total: 253
Average: 84.3
Trace: 78 + 91 + 84 = 253, and 253 / 3 = 84.333..., which :.1f shows as 84.3. The / operator is used for the average because the average is usually not a whole number; 253 // 3 would silently give 84. The comma in print("Total:", total) inserts one space between its items. Two options change that spacing:追踪:78 + 91 + 84 = 253,253 / 3 = 84.333...,:.1f 将其显示为 84.3。平均值使用 /,因为平均值通常不是整数;253 // 3 会悄悄得到 84。print("Total:", total) 中的逗号会在各项之间插入一个空格。有两个选项可以改变这种间距:
print("A", "B", "C") # A B C
print("A", "B", "C", sep="-") # A-B-C
print("Loading", end="...") # prints no newline
print("done") # the line now reads: Loading...done
Common error: leaving out int(). Then s1 + s2 + s3 joins the typed text, giving "788184", and total / 3 raises a TypeError.常见错误:漏掉 int()。这样 s1 + s2 + s3 会把输入的文本连接起来,得到 "788184",而 total / 3 会引发 TypeError。
Command words: "predict the output" wants the exact text printed, including the spaces that print inserts and the .0 on a float; "write" wants a complete program that converts each input. Common errors: omitting int() or float() so numbers are joined as text, and forgetting that print("a", "b") separates items with a space.
指令词:"预测输出"要求写出准确打印的文本,包括 print 插入的空格以及浮点数上的 .0;"编写"要求写出对每个输入都做转换的完整程序。常见错误:漏掉 int() 或 float() 导致数字被当作文本连接,以及忘记 print("a", "b") 用空格分隔各项。
The user types 4. What does n = input() followed by print(n + n) print?用户输入 4。n = input() 后接 print(n + n) 会打印什么?
44. The value of n is the string "4", and + joins two strings.
44。n 的值是字符串 "4",而 + 连接两个字符串。
What is printed by print("Hi", end="!") followed by print("there")?print("Hi", end="!") 后接 print("there") 会打印什么?
Hi!there on one line. The option end="!" replaces the newline that print normally adds.
同一行上打印 Hi!there。选项 end="!" 替换了 print 通常添加的换行。
A program runs int(input()) and the user types 3.5. Which error occurs, and what is one fix?程序运行 int(input()),用户输入 3.5。会发生什么错误?有什么修复方法?
A ValueError, because the text "3.5" is not a whole number. Fix: read it with float(input()), or use int(float(input())) to get 3.
ValueError,因为文本 "3.5" 不是整数。修复:用 float(input()) 读取,或用 int(float(input())) 得到 3。
n = input("Enter a number: ") then result = n * 2. If the user types 5, what is result?一名学生写道:n = input("输入一个数字:") 然后 result = n * 2。如果用户输入 5,result 是什么?input() returns a string. So n = "5" (string). In Python, "5" * 2 is string repetition: "55". To get the integer 10, you need n = int(input(...)) first.input() 返回字符串。所以 n = "5"(字符串)。在 Python 中,"5" * 2 是字符串重复:"55"。要得到整数 10,需要先 n = int(input(...))。input() always returns a string. String * integer = repeated string in Python, not arithmetic multiplication. Convert first with int() or float().input() 总是返回字符串。Python 中字符串 * 整数 = 重复字符串,而不是算术乘法。先用 int() 或 float() 转换。age?哪行代码能正确地从用户读取整数到变量 age?int(input("Age: ")) reads the string typed by the user and immediately converts it to an integer. Option A leaves it as a string; option C assigns the return value of print (which is None); option D gives a float (e.g., 17.0, not 17).int(input("年龄:")) 读取用户输入的字符串并立即转换为整数。选项 A 将其保留为字符串;选项 C 赋值 print 的返回值(即 None);选项 D 给出浮点数(如 17.0,而非 17)。Operators: Arithmetic and Relational运算符:算术与关系
- Evaluate an expression by applying operator precedence: parentheses, then
**, then* / // %left to right, then+ -. - Compute
//and%for positive and negative operands. - Use
//and%to split a total into whole units and a remainder. - Write relational expressions that return
TrueorFalse, such as a divisibility test.
- 运用运算符优先级求表达式的值:先括号,再
**,再从左到右的* / // %,最后+ -。 - 计算正数和负数操作数的
//与%。 - 用
//和%把总量拆成整数单位和余数。 - 编写返回
True或False的关系表达式,例如整除性测试。
- Arithmetic:算术运算符:
+add,-subtract,*multiply,/true divide (always float),//floor divide (integer result),%remainder,**power. BC CS10 Content (verbatim): "precedence of arithmetic operators." AB CSE1110 outcome 2.4.6: "use assignment, arithmetical … operators … to process data."+加,-减,*乘,/真除(总是浮点数),//整除(整数结果),%余数,**幂。BC CS10 内容(原文):"算术运算符优先级。" AB CSE1110 结果 2.4.6:"使用赋值、算术……运算符……处理数据。" - Relational (comparison):关系(比较)运算符:
==equal,!=not equal,<less than,>greater than,<=less-or-equal,>=greater-or-equal. Always returnTrueorFalse. ON ICS3U A1.4 names all six. BC CS10 Content (verbatim): "assignment and relational operators."==等于,!=不等于,<小于,>大于,<=小于等于,>=大于等于。总是返回True或False。ON ICS3U A1.4 列出所有六种。BC CS10 内容(原文):"赋值与关系运算符。" - PEMDAS / BODMAS order:运算优先级(PEMDAS/BODMAS): Parentheses → Exponents → Multiply/Divide → Add/Subtract. When in doubt, add parentheses.括号 → 指数 → 乘/除 → 加/减。有疑问时,加括号。
Worked Example 7: Operator results table例题 7:运算符结果表
Trace each expression given a = 17 and b = 5.给定 a = 17,b = 5,追踪每个表达式。
a = 17
b = 5
print(a + b) # 22 (addition / 加法)
print(a - b) # 12 (subtraction / 减法)
print(a * b) # 85 (multiplication / 乘法)
print(a / b) # 3.4 (true divide, always float / 真除,始终浮点数)
print(a // b) # 3 (floor divide, integer quotient / 整除,整数商)
print(a % b) # 2 (remainder: 17 = 3*5 + 2 / 余数:17 = 3*5 + 2)
print(a ** 2) # 289 (power: 17² / 幂:17²)
print(a > b) # True (relational / 关系)
print(a == 17) # True
print(a != b) # True
print(b >= 10) # False
Key distinction: a / b gives 3.4 (float). a // b gives 3 (int, rounds down). a % b gives the leftover 2. Knowing // and % is essential for problems like "how many whole hours in 200 minutes?" (200 // 60 = 3) and "how many minutes left over?" (200 % 60 = 20).关键区别:a / b 给出 3.4(浮点数)。a // b 给出 3(整数,向下取整)。a % b 给出余数 2。掌握 // 和 % 对解决"200 分钟有几个完整小时?"(200 // 60 = 3)和"剩余几分钟?"(200 % 60 = 20)等问题至关重要。
Worked Example 8: Precedence, floor division and remainder with negatives例题 8:优先级、整除与负数余数
Problem: (a) evaluate 10 - 2 * 3 ** 2 and (10 - 2) * 3 ** 2, showing the order of the steps; (b) evaluate -17 // 5, -17 % 5, 17 // -5 and 17 % -5; (c) convert 200 minutes to hours and minutes.问题:(a) 求 10 - 2 * 3 ** 2 和 (10 - 2) * 3 ** 2 的值,并写出步骤顺序;(b) 求 -17 // 5、-17 % 5、17 // -5 和 17 % -5;(c) 把 200 分钟换算成小时和分钟。
(a) In 10 - 2 * 3 ** 2 the operator ** binds tightest, so 3 ** 2 = 9 first; then 2 * 9 = 18; then 10 - 18 = -8. Figure 2 shows this as a tree: operators lower in the tree run first. With the parentheses, 10 - 2 = 8 runs first, so the result is 8 * 9 = 72.(a) 在 10 - 2 * 3 ** 2 中,** 结合最紧,所以先算 3 ** 2 = 9;然后 2 * 9 = 18;最后 10 - 18 = -8。图 2 把它画成树:树中位置更低的运算符先执行。加上括号后,先算 10 - 2 = 8,结果是 8 * 9 = 72。
(b) The operator // rounds down, toward negative infinity, not toward zero. Since -17 / 5 = -3.4, the floor is -4. The remainder always satisfies a == (a // b) * b + a % b, so -17 % 5 = -17 - (-4 * 5) = 3. In the same way 17 // -5 = -4 and 17 % -5 = 17 - (-4 * -5) = -3: a nonzero remainder takes the sign of the divisor.(b) 运算符 // 向下取整,即朝负无穷方向,而不是朝零方向。因为 -17 / 5 = -3.4,向下取整得 -4。余数始终满足 a == (a // b) * b + a % b,所以 -17 % 5 = -17 - (-4 * 5) = 3。同理 17 // -5 = -4,17 % -5 = 17 - (-4 * -5) = -3:非零余数的符号与除数相同。
(c) 200 // 60 = 3 whole hours and 200 % 60 = 20 minutes left over, so 200 minutes is 3 h 20 min. Check: 3 * 60 + 20 = 200.(c) 200 // 60 = 3 个完整小时,200 % 60 = 20 分钟剩余,所以 200 分钟是 3 小时 20 分钟。验算:3 * 60 + 20 = 200。
print(10 - 2 * 3 ** 2) # -8
print((10 - 2) * 3 ** 2) # 72
print(-17 // 5, -17 % 5) # -4 3
print(17 // -5, 17 % -5) # -4 -3
print(7.0 // 2) # 3.0
total = 200
print(total // 60, total % 60) # 3 20
Common errors: reading 10 - 2 * 3 from left to right as (10 - 2) * 3, and expecting -17 // 5 to be -3.常见错误:把 10 - 2 * 3 从左到右读成 (10 - 2) * 3,以及以为 -17 // 5 等于 -3。
Command words: "evaluate" wants the final value and its type, "trace" wants each step in precedence order, and "write an expression" wants valid Python. Common errors: reading 10 - 2 * 3 as (10 - 2) * 3, assuming // truncates toward zero for negative numbers (it rounds down), and writing = instead of == in a test.
指令词:"求值"要求写出最终值及其类型,"追踪"要求按优先级顺序列出每一步,"写出表达式"要求写出有效的 Python。常见错误:把 10 - 2 * 3 读成 (10 - 2) * 3,以为负数的 // 向零截断(实际向下取整),以及在测试中把 == 写成 =。
Evaluate 2 + 3 * 4 ** 2 // 5 and show the order of the steps.求 2 + 3 * 4 ** 2 // 5 的值,并写出步骤顺序。
4 ** 2 = 16; then 3 * 16 = 48 and 48 // 5 = 9 (left to right at the same level); then 2 + 9 = 11.
4 ** 2 = 16;然后 3 * 16 = 48,48 // 5 = 9(同一级别从左到右);最后 2 + 9 = 11。
What are -7 // 2 and -7 % 2?-7 // 2 和 -7 % 2 各是多少?
-7 // 2 = -4 because -3.5 rounds down, and -7 % 2 = 1. Check: (-4) * 2 + 1 = -7.
-7 // 2 = -4,因为 -3.5 向下取整;-7 % 2 = 1。验算:(-4) * 2 + 1 = -7。
Write an expression that is True when n is a multiple of 3, and give its value for n = 14.写出一个当 n 是 3 的倍数时为 True 的表达式,并给出 n = 14 时它的值。
n % 3 == 0. For n = 14, 14 % 3 = 2, so the expression is False.
n % 3 == 0。当 n = 14 时,14 % 3 = 2,所以表达式为 False。
10 % 3 in Python?Python 中 10 % 3 的值是多少?% is the remainder (modulo) operator. 10 = 3 × 3 + 1, so the remainder is 1. Use % to check divisibility: if n % 2 == 0 then n is even.% 是余数(取模)运算符。10 = 3 × 3 + 1,所以余数是 1。使用 % 检查整除性:如果 n % 2 == 0,则 n 是偶数。True if x = 8?当 x = 8 时,哪个表达式结果为 True?8 % 2 == 0: 8 ÷ 2 = 4 remainder 0, so True. This is the standard even-number check. The others: 8 > 10 is False; 8 == 9 is False; 8 != 8 is False.8 % 2 == 0:8 ÷ 2 = 4 余 0,所以为 True。这是标准的偶数检查。其他:8 > 10 为 False;8 == 9 为 False;8 != 8 为 False。Going deeper: operator precedence pitfalls深入:运算符优先级陷阱
Python follows standard mathematical precedence (PEMDAS), but several edge cases trip beginners. (1) 2 ** 3 ** 2 is 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 64; exponentiation is right-associative. (2) -2 ** 2 is -(2 ** 2) = -4, not (-2) ** 2 = 4; the unary minus has lower precedence than **. (3) 7 / 2 * 3 is (7 / 2) * 3 = 10.5, evaluated left-to-right at the same level. Always use explicit parentheses in expressions that mix ** with unary minus or where the reader might be confused. BC CS10 Content (verbatim): "order of operations, precedence of arithmetic operators." AB CSE1110 2.4.6 implicitly covers this through the requirement to correctly use arithmetical operators.Python 遵循标准数学优先级(PEMDAS),但有几个边界情况会让初学者犯错。(1) 2 ** 3 ** 2 是 2 ** (3 ** 2) = 2 ** 9 = 512,而非 (2 ** 3) ** 2 = 64,指数运算是右结合的。(2) -2 ** 2 是 -(2 ** 2) = -4,而非 (-2) ** 2 = 4,一元负号的优先级低于 **。(3) 7 / 2 * 3 是 (7 / 2) * 3 = 10.5,在同一优先级从左到右求值。在混合 ** 和一元负号或读者可能感到困惑的表达式中,始终使用显式括号。BC CS10 内容(原文):"运算顺序,算术运算符优先级。" AB CSE1110 2.4.6 通过正确使用算术运算符的要求隐式涵盖这一点。
Type Conversion and Casting类型转换与强制转换
- Predict the result of
int(),float(),str(),round()andbool()applied to given values. - Explain the difference between truncating with
int()and rounding withround(), including negative numbers. - State the rule
round()uses for an exact half. - Decide whether a faulty conversion raises TypeError or ValueError, and write the fix.
- 预测
int()、float()、str()、round()和bool()作用于给定值的结果。 - 解释用
int()截断与用round()四舍五入的区别,包括负数。 - 说出
round()对恰好一半的情况所用的规则。 - 判断错误的转换会引发 TypeError 还是 ValueError,并写出修复方法。
int(x)int(x): converts x to integer.int(3.9)→3(truncates, does NOT round).int("42")→42.int("3.9")→ ValueError (cannot parse a decimal string to int directly).:将 x 转换为整数。int(3.9)→3(截断,不四舍五入)。int("42")→42。int("3.9")→ ValueError(不能直接将小数字符串解析为整数)。float(x)float(x): converts x to float.float(7)→7.0.float("3.14")→3.14. Safe for any numeric string.:将 x 转换为浮点数。float(7)→7.0。float("3.14")→3.14。对任意数字字符串均安全。str(x)str(x): converts x to string.str(42)→"42". Needed when you want to concatenate a number into a string:"Score: " + str(score).:将 x 转换为字符串。str(42)→"42"。将数字拼入字符串时需要:"分数:" + str(score)。
Worked Example 9: Conversion errors and fixes例题 9:转换错误与修复
Each buggy snippet below causes a TypeError or ValueError. Identify the bug and the fix.以下每个有错误的代码片段会导致 TypeError 或 ValueError。识别错误并给出修复方案。
Bug 1: adding string to int.错误 1:将字符串与整数相加。
# BUG: input() returns a string
age = input("Enter age: ")
new_age = age + 1 # TypeError: can only concatenate str (not "int") to str
# FIX:
age = int(input("Enter age: "))
new_age = age + 1 # works correctly
Bug 2: int() on a decimal string.错误 2:对小数字符串使用 int()。
# BUG:
price = int(input("Enter price: ")) # user types "9.99" → ValueError
# FIX: use float() first, then convert if needed
price = float(input("Enter price: ")) # works for "9.99"
Bug 3: concatenating number into message.错误 3:将数字拼接到消息中。
# BUG:
score = 95
message = "Your score is " + score # TypeError
# FIX:
message = "Your score is " + str(score) # works
# OR use an f-string (simpler):
message = f"Your score is {score}" # also works
The pattern is: whenever you mix types in an expression, Python raises a TypeError unless you explicitly convert. Type errors are among the most common beginner mistakes, and the easiest to fix once you know what the message means.规律是:每当你在表达式中混合类型,除非你显式转换,否则 Python 会引发 TypeError。类型错误是最常见的初学者错误之一,一旦你理解了错误消息的含义,也是最容易修复的。
Worked Example 10: Truncating, rounding and converting step by step例题 10:截断、舍入与逐步转换
Problem: predict the output of each line in the first block, then say which of the three lines in the second block fail and with which error.问题:预测第一段代码中每一行的输出,然后指出第二段代码中的三行哪些会失败,以及各引发什么错误。
print(int(3.9), int(-3.9)) # 3 -3
print(round(3.9), round(-3.9)) # 4 -4
print(round(2.5), round(3.5)) # 2 4
print(round(3.14159, 2)) # 3.14
print(float("3.9"), int(float("3.9"))) # 3.9 3
print(float(3), str(3.0)) # 3.0 3.0
print(bool(0), bool(""), bool("False")) # False False True
print(str(5) + str(5), int("5") + int("5")) # 55 10
int() truncates toward zero, so int(-3.9) is -3. round() goes to the nearest integer, so round(-3.9) is -4. For an exact half, Python 3 rounds to the nearest even integer: round(2.5) is 2 and round(3.5) is 4 (some other languages round halves up, so do not assume the same result there). int("3.9") fails, but int(float("3.9")) works in two steps. bool() gives False for 0 and the empty string and True for any non-empty text, including "False".int() 向零截断,所以 int(-3.9) 是 -3。round() 取最接近的整数,所以 round(-3.9) 是 -4。对于恰好一半的情况,Python 3 取最接近的偶数:round(2.5) 是 2,round(3.5) 是 4(有些其他语言把一半向上舍入,所以不要假设那里结果相同)。int("3.9") 会失败,但 int(float("3.9")) 分两步即可成功。bool() 对 0 和空字符串给出 False,对任何非空文本(包括 "False")给出 True。
int("7.5") # ValueError: invalid literal for int() with base 10: '7.5'
"5" + 1 # TypeError: can only concatenate str (not "int") to str
1 + "5" # TypeError: unsupported operand type(s) for +: 'int' and 'str'
A ValueError means the type is acceptable but the content is not: "7.5" is text, so int() accepts it as input, but it does not describe a whole number. A TypeError means the operation does not support the combination of types: a string and an int cannot be added. Fixes: int(float("7.5")) gives 7, and "5" + str(1) gives "51" (or int("5") + 1 gives 6, if arithmetic was meant).ValueError 表示类型可接受但内容不行:"7.5" 是文本,所以 int() 接受它作为输入,但它并不表示整数。TypeError 表示该运算不支持这种类型组合:字符串和整数不能相加。修复:int(float("7.5")) 得到 7,"5" + str(1) 得到 "51"(如果本意是算术,则 int("5") + 1 得到 6)。
Command words: "state the result" wants the value and its type, "identify the error" wants the error name (TypeError or ValueError) and the line, and "fix" wants corrected code. Common errors: expecting int(3.9) to be 4, expecting int("3.9") to work, and expecting round(2.5) to be 3.
指令词:"写出结果"要求写出值及其类型,"指出错误"要求写出错误名称(TypeError 或 ValueError)和出错的那一行,"修复"要求写出更正后的代码。常见错误:以为 int(3.9) 等于 4,以为 int("3.9") 可以成功,以及以为 round(2.5) 等于 3。
What happens with int("7.5"), and how do you get the whole-number part 7 from that text?int("7.5") 会发生什么?如何从该文本得到整数部分 7?
It raises a ValueError. Convert in two steps: int(float("7.5")) gives 7.
引发 ValueError。分两步转换:int(float("7.5")) 得到 7。
What are round(6.5) and round(7.5)?round(6.5) 和 round(7.5) 各是多少?
6 and 8. Both are exact halves, and Python 3 rounds an exact half to the nearest even integer.
6 和 8。两者都是恰好一半,Python 3 将恰好一半舍入到最接近的偶数。
Compare str(12) + str(3) with 12 + 3.比较 str(12) + str(3) 与 12 + 3。
The first joins text and gives the str "123"; the second adds numbers and gives the int 15.
前者连接文本,得到字符串 "123";后者做数字加法,得到整数 15。
int(7.9) return in Python?Python 中 int(7.9) 返回什么?int() truncates toward zero; it drops the decimal part without rounding. int(7.9) → 7, not 8. int(-7.9) → -7, not -8. Use round() if you need nearest-integer rounding.int() 向零截断,丢掉小数部分,不四舍五入。int(7.9) → 7,不是 8。int(-7.9) → -7,不是 -8。如果需要四舍五入到最近整数,使用 round()。result = "Total: " + 42. What happens?一名学生写道 result = "总计:" + 42。会发生什么?"Total: " + str(42) or f"Total: {42}".Python 不会自动将整数转换为字符串。将字符串和整数相加会引发 TypeError。修复:"总计:" + str(42) 或 f"总计:{42}"。Going deeper: widening, narrowing, and finite representation Honors: ICS4U A1.2 / A1.4深入:扩宽、收窄与有限表示 荣誉:ICS4U A1.2 / A1.4
In Java and other statically-typed languages, conversion is classified as widening (safe, automatic) or narrowing (potentially lossy, requires an explicit cast). Widening: int → long → float → double: the value is converted automatically, though int or long to float can lose precision. Narrowing: double → int: you lose the fractional part and may overflow. Java requires explicit casting syntax: int x = (int) 3.9; → x = 3. ON ICS4U A1.2 (verbatim): "demonstrate an understanding of type conversion (e.g., string-to-integer, character-to-integer, integer-to-character, floating point-to-integer, casting in an inheritance hierarchy)." A1.4 adds: "demonstrate an understanding of the limitations of finite data representations (e.g., integer bounds, precision of floating-point real numbers, rounding errors)." In Python, floating-point precision matters too: 0.1 + 0.2 gives 0.30000000000000004 in Python (IEEE 754 representation artifact). Never compare floats with ==; use abs(a - b) < 0.0001 instead.在 Java 和其他静态类型语言中,转换分为扩宽(安全,自动)和收窄(可能有损,需要显式转换)。扩宽:int → long → float → double:自动转换,但 int 或 long 转为 float 可能损失精度。收窄:double → int:丢失小数部分,可能溢出。Java 需要显式转换语法:int x = (int) 3.9; → x = 3。ON ICS4U A1.2(原文):"展示对类型转换的理解(如字符串到整数、字符到整数、整数到字符、浮点数到整数、继承层次中的类型转换)。" A1.4 补充:"展示对有限数据表示局限的理解(如整数界限、浮点实数精度、舍入误差)。"Python 中浮点精度也很重要:0.1 + 0.2 在 Python 中给出 0.30000000000000004(IEEE 754 表示的副产品)。永远不要用 == 比较浮点数;改用 abs(a - b) < 0.0001。
Constants and Naming Conventions常量与命名规范
- State the rules for a legal Python name: letters, digits and underscores, not starting with a digit, no spaces or hyphens, not a keyword, and case-sensitive.
- Apply
snake_caseto variables andUPPER_SNAKE_CASEto constants. - Replace a magic number with a named constant and say why that helps.
- Explain that Python does not stop a program from reassigning a constant.
- 说出合法 Python 名称的规则:由字母、数字和下划线组成,不以数字开头,没有空格或连字符,不是关键字,并且区分大小写。
- 对变量使用
snake_case,对常量使用UPPER_SNAKE_CASE。 - 用具名常量替换魔法数字,并说明这样做的好处。
- 解释 Python 不会阻止程序重新给常量赋值。
- snake_case for variables and functions变量和函数用蛇形命名法(snake_case): all lowercase, words joined with underscores:
student_name,total_score,calculate_average. Python style guide (PEP 8) mandates this. ON ICS3U A2.2 requires "use appropriate internal and external documentation.":全小写,单词用下划线连接:student_name、total_score、calculate_average。Python 风格指南(PEP 8)规定如此。ON ICS3U A2.2 要求"使用适当的内部和外部文档"。 - UPPER_SNAKE_CASE for constants常量用全大写蛇形命名法(UPPER_SNAKE_CASE): a constant is a value that should never change during the program's run.
TAX_RATE = 0.13,MAX_SCORE = 100. Python has no true constant keyword (unlike Java'sfinal), but the convention signals intent. ON ICS3U A1.1: "use constants … correctly in computer programs." AB CSE1110 2.4.4: "use appropriate variables and constants to hold data.":常量是程序运行期间不应改变的值。TAX_RATE = 0.13、MAX_SCORE = 100。Python 没有真正的常量关键字(不像 Java 的final),但该约定传达了意图。ON ICS3U A1.1:"在计算机程序中正确使用常量……" AB CSE1110 2.4.4:"使用适当的变量和常量保存数据。" - Descriptive over short描述性优先于简短:
widthbeatsw;student_agebeatsa. The exception: loop countersi,j,kare universally understood. AB CSE1110 outcome 2.4.2: "use appropriate internal and external documentation.":width优于w;student_age优于a。例外:循环计数器i、j、k是公认的。AB CSE1110 结果 2.4.2:"使用适当的内部和外部文档。"
Worked Example 11: Refactoring with constants and clear names例题 11:用常量和清晰命名重构代码
The first version is hard to read. The second version uses constants and descriptive names to make the intent clear.第一版难以阅读。第二版使用常量和描述性命名使意图清晰。
Version 1: hard to read ("magic numbers").版本 1:难以阅读("魔法数字")。
p = float(input())
t = p * 0.13
f = p + t
print(f)
What is 0.13? What is p, t, f? A reader cannot tell without context.0.13 是什么?p、t、f 是什么?读者没有上下文无法判断。
Version 2: clear names and a named constant.版本 2:清晰命名与具名常量。
TAX_RATE = 0.13 # Ontario HST rate, a constant
price_before_tax = float(input("Enter price before tax: "))
tax_amount = price_before_tax * TAX_RATE
final_price = price_before_tax + tax_amount
print("Final price:", final_price)
Now the code documents itself. If the tax rate changes to 0.15, you change one line (TAX_RATE = 0.15) and every calculation updates automatically. This is why constants matter more than just style; they prevent "change in one place, miss it in ten" bugs.现在代码自我说明。如果税率变为 0.15,只需更改一行(TAX_RATE = 0.15),所有计算自动更新。这就是常量比样式更重要的原因,它们防止了"改一处、漏十处"的错误。
Worked Example 12: Legal names and a circle calculator with a constant例题 12:合法名称与带常量的圆计算器
Problem: (a) for each name decide whether it is a legal Python name and whether it follows convention: score1, 1st_place, total-score, class, Total, MAX_ATTEMPTS. (b) Write a program that prints the area and circumference of a circle of radius 5 using a named constant.问题:(a) 对每个名称判断它是否是合法的 Python 名称,以及是否符合约定:score1、1st_place、total-score、class、Total、MAX_ATTEMPTS。(b) 用具名常量编写程序,打印半径为 5 的圆的面积和周长。
(a) Names.(a) 名称。
score1: legal, since digits are allowed after the first character, and it follows snake_case.score1:合法,因为首字符之后允许出现数字,并且符合蛇形命名法。1st_place: illegal, because a name cannot start with a digit.1st_place:不合法,因为名称不能以数字开头。total-score: illegal as a name, because Python reads the hyphen as subtraction (totalminusscore).total-score:作为名称不合法,因为 Python 把连字符读作减号(total减score)。class: illegal, because it is a reserved keyword.class:不合法,因为它是保留关键字。Total: legal, but different fromtotalbecause names are case-sensitive; capitalised names are conventionally used for classes, so avoid it for a variable.Total:合法,但与total不同,因为名称区分大小写;首字母大写的名称按约定用于类,所以不要用于变量。MAX_ATTEMPTS: legal, and the convention for a constant.MAX_ATTEMPTS:合法,并且是常量的约定写法。
(b) Program.(b) 程序。
PI = 3.14159
radius = 5
area = PI * radius ** 2
circumference = 2 * PI * radius
print(f"Area: {area:.2f}") # Area: 78.54
print(f"Circumference: {circumference:.2f}") # Circumference: 31.42
The constant PI is written once, so improving its precision later means editing one line. Before formatting, area is 78.53975; :.2f rounds it to 78.54 for display only. Python's math module also provides math.pi. Naming the constant does not protect it: a later line PI = 3 would run without any error, because UPPER_SNAKE_CASE is only a signal to the reader.常量 PI 只写一次,所以以后要提高精度时只需改一行。格式化之前 area 是 78.53975;:.2f 仅为显示而把它舍入为 78.54。Python 的 math 模块也提供 math.pi。给常量命名并不能保护它:之后的一行 PI = 3 运行时不会有任何错误,因为全大写蛇形命名只是给读者的提示。
Command words: "identify" asks which names are legal and the reason each other name is not, "refactor" asks for the same behaviour with clearer names, and "justify" asks for a reason such as having one place to change. Common errors: a name that starts with a digit, a hyphen inside a name, using a keyword such as class as a variable, and thinking an UPPER_CASE name is protected from change.
指令词:"识别"要求指出哪些名称合法以及其余名称不合法的原因,"重构"要求在保持行为不变的前提下使用更清晰的名称,"说明理由"要求给出诸如只需在一处修改之类的理由。常见错误:名称以数字开头,名称中含连字符,把 class 之类的关键字当变量用,以及以为全大写名称不会被改动。
Which of total_2, 2_total, total 2 and total-2 are legal names?total_2、2_total、total 2 和 total-2 中哪些是合法名称?
Only total_2. The second starts with a digit, the third contains a space and the fourth contains a hyphen.
只有 total_2。第二个以数字开头,第三个含空格,第四个含连字符。
Rewrite fee = days * 0.25 so that the number 0.25 has a meaningful name.改写 fee = days * 0.25,使数字 0.25 有一个有意义的名称。
LATE_FEE_PER_DAY = 0.25, then fee = days * LATE_FEE_PER_DAY. A change of rate is now made in one place.
LATE_FEE_PER_DAY = 0.25,然后 fee = days * LATE_FEE_PER_DAY。费率变化时只需在一处修改。
A program sets TAX_RATE = 0.13 and later TAX_RATE = 0.15. Does Python report an error?程序设置 TAX_RATE = 0.13,之后又设置 TAX_RATE = 0.15。Python 会报错吗?
No. Python allows the reassignment, and the second value is used from then on. The upper-case name is a convention that tells readers not to change it.
不会。Python 允许重新赋值,此后使用第二个值。全大写名称只是提示读者不要改动它的约定。
student_age follows snake_case (all lowercase, underscores) and is self-documenting. StudentAge is PascalCase (used for class names in Python). sa is too short to be clear. STUDENT_AGE is reserved for constants.student_age 遵循蛇形命名法(全小写,下划线),且自我说明。StudentAge 是帕斯卡命名法(Python 中用于类名)。sa 太短不够清晰。STUDENT_AGE 保留给常量。MAX_STUDENTS = 30 than to use the number 30 directly throughout the code?为什么写 MAX_STUDENTS = 30 比在代码中直接使用数字 30 更好?Writing and Running Your First Program编写并运行你的第一个程序
- Apply the five-step pipeline (IPO, pseudocode, Python, known input, edge cases) to a new problem.
- Use
//and%to split a total into units and print it with zero-padded f-string fields such as{minutes:02d}. - Choose test inputs that include a typical case and the boundary cases (zero, just below a unit and exactly on a unit).
- Name the failure for non-numeric input (ValueError) and recognise an input the program does not guard against.
- 把五步流程(IPO、伪代码、Python、已知输入、边界情况)应用到新问题上。
- 用
//和%把总量拆成各个单位,并用{minutes:02d}这样补零的 f 字符串字段输出。 - 选择既包含典型情形又包含边界情形(零、刚好不足一个单位以及恰好一个单位)的测试输入。
- 说出非数字输入的错误名称(ValueError),并识别程序没有防范的输入。
- 1. State the problem in IPO form1. 用 IPO 形式陈述问题: identify inputs (what does the user supply?), process (what calculation?), output (what do we print?).:识别输入(用户提供什么?)、处理(什么计算?)、输出(打印什么?)。
- 2. Write pseudocode2. 写伪代码: use plain keywords (INPUT, SET, OUTPUT). No Python syntax yet.:使用普通关键字(INPUT、SET、OUTPUT)。还不用 Python 语法。
- 3. Translate to Python3. 翻译为 Python: each pseudocode line becomes one or two Python lines. Remember:
input()always returns str, so convert immediately.:每行伪代码变成一两行 Python。记住:input()总是返回字符串,立即转换。 - 4. Run with a known input4. 用已知输入运行: use a value you can check by hand. Does the output match your IPO expectation?:使用你能手工验证的值。输出是否符合 IPO 预期?
- 5. Test edge cases5. 测试边界情况: try 0, negative numbers, and non-numeric text to see how the program behaves. AB CSE1110 outcome 2.4.1: "maintain the IPO structure of the algorithm.":尝试 0、负数和非数字文本,观察程序如何反应。AB CSE1110 结果 2.4.1:"维护算法的 IPO 结构。"
Worked Example 13: BMI calculator: full pipeline例题 13:BMI 计算器:完整流程
Build a Body Mass Index calculator. BMI = weight (kg) / height (m)². Walk through all five steps.构建一个体重指数计算器。BMI = 体重(千克)/ 身高(米)²。逐步完成全部五个步骤。
Step 1: IPO.步骤 1:IPO。
- Input: weight in kg (float), height in m (float).输入:体重(千克,浮点数),身高(米,浮点数)。
- Process: BMI = weight / height².处理:BMI = 体重 / 身高²。
- Output: BMI rounded to 1 decimal place.输出:BMI 保留 1 位小数。
Step 2: Pseudocode.步骤 2:伪代码。
INPUT weight_kg
INPUT height_m
SET bmi TO weight_kg / (height_m * height_m)
OUTPUT bmi (rounded to 1 decimal)
Step 3: Python translation.步骤 3:Python 翻译。
weight_kg = float(input("Weight in kg: "))
height_m = float(input("Height in m: "))
bmi = weight_kg / (height_m ** 2)
print(f"BMI = {bmi:.1f}")
The :.1f format specifier rounds the float to 1 decimal place in the output string.:.1f 格式说明符在输出字符串中将浮点数舍入到 1 位小数。
Step 4: run with known input.步骤 4:用已知输入运行。
# weight = 70 kg, height = 1.75 m
# BMI = 70 / (1.75)^2 = 70 / 3.0625 ≈ 22.9
# Expected output: BMI = 22.9 ✓
Step 5: edge case: height = 0.步骤 5:边界情况:身高 = 0。
# height_m = 0 → division by zero → ZeroDivisionError
# Guard: add an if-check before the calculation (covered in Control Flow guide)
Spotting the edge case now (before writing any more code) is exactly what AB CSE1110 outcome 2.4.1 ("maintain the IPO structure") and ON ICS3U A2.1 ("incorporate user input, processing, and screen output") require.现在就发现边界情况(在写更多代码之前)正是 AB CSE1110 结果 2.4.1("维护 IPO 结构")和 ON ICS3U A2.1("包含用户输入、处理和屏幕输出")所要求的。
Worked Example 14: Seconds to hours, minutes and seconds例题 14:秒数换算为时、分、秒
Problem: write a program that reads a whole number of seconds and prints it as HH:MM:SS. Work through all five steps and check 3725 seconds by hand.问题:编写程序,读取整数秒数并以 HH:MM:SS 形式打印。完成全部五个步骤,并手工验算 3725 秒。
Step 1: IPO.步骤 1:IPO。
- Input:
seconds_total, a whole number.输入:seconds_total,一个整数。 - Process: there are 3600 seconds in an hour, so
hours = seconds_total // 3600; the leftover isseconds_total % 3600, which splits again into minutes (// 60) and seconds (% 60).处理:一小时有 3600 秒,所以hours = seconds_total // 3600;剩余部分是seconds_total % 3600,再拆分为分钟(// 60)和秒(% 60)。 - Output: HH:MM:SS with each part padded to two digits.输出:HH:MM:SS,每一部分补足两位数字。
Step 2: pseudocode.步骤 2:伪代码。
INPUT seconds_total
SET hours TO seconds_total // 3600
SET remaining TO seconds_total % 3600
SET minutes TO remaining // 60
SET seconds TO remaining % 60
OUTPUT hours, minutes, seconds as HH:MM:SS
Step 3: Python.步骤 3:Python。
seconds_total = int(input("Seconds: "))
hours = seconds_total // 3600
remaining = seconds_total % 3600
minutes = remaining // 60
seconds = remaining % 60
print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
The field :02d prints an integer in at least two places, filling with a leading zero, so 5 prints as 05.字段 :02d 以至少两位输出整数,不足时用前导零补齐,所以 5 输出为 05。
Step 4: known input.步骤 4:已知输入。
For 3725: hours = 3725 // 3600 = 1, remaining = 3725 % 3600 = 125, minutes = 125 // 60 = 2, seconds = 125 % 60 = 5. The program prints 01:02:05. Check: 1 * 3600 + 2 * 60 + 5 = 3725.对于 3725:hours = 3725 // 3600 = 1,remaining = 3725 % 3600 = 125,minutes = 125 // 60 = 2,seconds = 125 % 60 = 5。程序打印 01:02:05。验算:1 * 3600 + 2 * 60 + 5 = 3725。
Step 5: edge cases.步骤 5:边界情况。
input program prints
3725 01:02:05
0 00:00:00
59 00:00:59
3600 01:00:00
86399 23:59:59
-1 -1:59:59 (wrong: a negative time is invalid)
abc ValueError at int(input(...))
The boundary values 0, 59, 3600 and 86399 behave correctly. The input -1 exposes a gap: floor division makes hours = -1, so the program prints -1:59:59, which is not a valid time. The program needs a guard that rejects negative values (covered in the Control Flow guide). The input abc makes int() raise a ValueError.边界值 0、59、3600 和 86399 的结果都正确。输入 -1 暴露了一个漏洞:整除使 hours = -1,所以程序打印 -1:59:59,这不是有效的时间。程序需要一个拒绝负值的保护(在控制流指南中介绍)。输入 abc 会使 int() 引发 ValueError。
Command words: "design" asks for the IPO and pseudocode before any code, "test" asks for inputs together with the expected outputs, and "state an edge case" asks for a specific input and what goes wrong. Common errors: not working out the expected output by hand first, so a wrong result cannot be noticed, and testing only typical values.
指令词:"设计"要求先写出 IPO 和伪代码再写代码,"测试"要求给出输入及其预期输出,"说明边界情况"要求给出具体输入以及会出什么问题。常见错误:没有先手工算出预期输出,导致错误结果无法被发现,以及只测试典型值。
What does the program print for 7384 seconds?对于 7384 秒,程序打印什么?
7384 // 3600 = 2, the remainder is 184, so minutes are 184 // 60 = 3 and seconds are 184 % 60 = 4. It prints 02:03:04.
7384 // 3600 = 2,余数为 184,所以分钟是 184 // 60 = 3,秒是 184 % 60 = 4。程序打印 02:03:04。
What does f"{5:02d}" give, and what does f"{12:02d}" give?f"{5:02d}" 的结果是什么?f"{12:02d}" 的结果是什么?
"05" and "12". The field pads with a zero only when the number has fewer than two digits.
"05" 和 "12"。只有当数字不足两位时,该字段才用零补齐。
Give two edge-case inputs for the seconds program with the output you expect for each.为秒数换算程序给出两个边界情况输入,并写出各自预期的输出。
For example 0 should print 00:00:00, and 86399 should print 23:59:59. Other good choices are 59 and 3600.
例如 0 应打印 00:00:00,86399 应打印 23:59:59。其他合适的选择还有 59 和 3600。
age = input("Age: "). The user enters "abc". What happens when the program later executes next_year = age + 1?程序用 age = input("年龄:") 询问用户年龄。用户输入"abc"。当程序随后执行 next_year = age + 1 时会发生什么?age is the string "abc" (input always returns a string). Adding a string and an integer raises a TypeError. The correct code would be age = int(input("Age: ")), but even that would raise ValueError when the user types "abc". Both are edge cases to handle.age 是字符串 "abc"(input 总是返回字符串)。将字符串和整数相加会引发 TypeError。正确代码应为 age = int(input("年龄:")),但当用户输入"abc"时,这也会引发 ValueError。两者都是需要处理的边界情况。Going deeper: f-strings and formatted output深入:f 字符串与格式化输出
Python 3.6+ f-strings (f"...") are the cleanest way to embed variable values in output text. Inside the curly braces you can put any expression and an optional format specifier after a colon. Key format specifiers: :.2f = 2 decimal places (for currency); :d = integer; :>10 = right-align in a field of width 10; :, = thousands separator. Examples: f"Price: ${price:.2f}" → Price: $9.99. f"Count: {count:,}" → Count: 1,234,567. BC CP11 Content (verbatim): "programming language constructs to support input/output" and "translation of design specifications into source code", formatted output is a core part of that translation. AB CSE1110 2.4.7 requires using "output commands … to display processed data", f-strings are the most readable way to do this in Python.Python 3.6+ 的 f 字符串(f"...")是在输出文本中嵌入变量值的最简洁方式。在花括号内可以放任意表达式,以及冒号后的可选格式说明符。关键格式说明符::.2f = 2 位小数(用于货币);:d = 整数;:>10 = 在宽度为 10 的字段中右对齐;:, = 千位分隔符。示例:f"价格:${price:.2f}" → 价格:$9.99。f"数量:{count:,}" → 数量:1,234,567。BC CP11 内容(原文):"支持输入/输出的编程语言构造"和"将设计规格转化为源代码",格式化输出是该翻译的核心部分。AB CSE1110 2.4.7 要求使用"输出命令……显示已处理数据",f 字符串是 Python 中最具可读性的实现方式。
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- IPO first, always.始终先做 IPO。 Before touching the keyboard, write down: what are the inputs? what is the calculation? what is the output? ON ICS3U A2.1 and AB CSE1110 2.4.1 both assess whether you maintain the IPO structure from start to finish.在触碰键盘之前,写下:输入是什么?计算是什么?输出是什么?ON ICS3U A2.1 和 AB CSE1110 2.4.1 都评估你是否从始至终维护 IPO 结构。
- Declare the type before you use the value.使用值之前声明类型。 Ask yourself: is this an int, float, str, or bool? Wrap
input()in the correct converter immediately. The single most common beginner mistake is forgetting to convert.问自己:这是整数、浮点数、字符串还是布尔值?立即将input()用正确的转换器包装。最常见的初学者错误是忘记转换。 - Check your operator.检查你的运算符。
=assigns.==compares./gives a float.//gives an integer.%gives the remainder. Mixing these is the top source of logic errors in this unit.=赋值。==比较。/给出浮点数。//给出整数。%给出余数。混淆这些是本单元逻辑错误的主要来源。
- Trace assignments step by step.逐步追踪赋值。 AP CSP AAP-1.B directly asks "what is the value of x after these lines?": the only safe technique is to trace each line in order. Never try to guess the final value by mental shortcut.AP CSP AAP-1.B 直接问"这几行后 x 的值是什么?":唯一安全的技术是按顺序追踪每一行。永远不要试图用心理捷径猜最终值。
- State the type before the value.先说类型再说值。 On a written assessment, when asked "what is the result of …", state the type as well as the value: "a string, '42'" or "an integer, 3". An answer that gives only the value hides whether you know the type.在书面测评中,当被问到"……的结果是什么"时,除了值之外也要说出类型:"字符串 '42'"或"整数 3"。只给出值的回答看不出你是否知道类型。
- Name the convention.说出命名规范。 When asked about naming in Python: variables/functions use snake_case; constants use UPPER_SNAKE_CASE; classes use PascalCase. Each convention is a separate fact to recall.被问到 Python 命名时:变量/函数用蛇形命名法;常量用全大写蛇形命名法;类用帕斯卡命名法。每种规范都是需要分别记住的一个知识点。
- Edge case = test the boundaries.边界情况 = 测试边界。 For every program you write, mentally test: what happens if the user enters 0? a negative number? a non-numeric string? Spotting and stating these matches what ON ICS3U A2.1 and AB CSE1110 2.4.1 ask for.对你编写的每个程序,在心里测试:如果用户输入 0 会怎样?负数?非数字字符串?发现并陈述这些,正符合 ON ICS3U A2.1 和 AB CSE1110 2.4.1 的要求。
- Use AP CSP pseudocode when the task asks for it.任务要求时使用 AP CSP 伪代码。 AP CSP uses its own keyword set: assignment is
←, display isDISPLAY(), Boolean values areTRUE/FALSE. Write from the reference sheet, not Python syntax.AP CSP 使用其自己的关键字集:赋值是←,显示是DISPLAY(),布尔值是TRUE/FALSE。从参考手册写,而不是 Python 语法。 - Show conversion explicitly.显式展示转换。 If your solution requires reading a number, write
int(input(...))orfloat(input(...))in full; never justinput(). Leaving out the conversion gives an incomplete answer, becauseinput()returns text.如果你的解决方案需要读取数字,完整写出int(input(...))或float(input(...)),永远不要只写input()。遗漏转换会使答案不完整,因为input()返回的是文本。
Flashcards闪卡
x = 5 stores 5 in x (assignment). x == 5 tests if x equals 5 (returns True/False). AP CSP AAP-1.B.x = 5 将 5 存入 x(赋值)。x == 5 测试 x 是否等于 5(返回 True/False)。AP CSP AAP-1.B。"42"?"42" 的类型?"42" ≠ 42 (int). Cannot do arithmetic on "42" directly.str(字符串)。引号总是创建字符串,无论内容是什么。"42" ≠ 42(整数)。不能直接对 "42" 进行算术运算。input() return?input() 返回什么?int(input(...)) or float(input(...)). AB CSE1110 2.4.5.总是字符串(str),无论用户输入什么。立即转换:int(input(...)) 或 float(input(...))。AB CSE1110 2.4.5。+ add · - subtract · * multiply · / true divide (float) · // floor divide (int) · % remainder · ** power. BC CS10 Content.+ 加 · - 减 · * 乘 · / 真除(浮点数)· // 整除(整数)· % 余数 · ** 幂。BC CS10 内容。17 % 5?17 % 5 等于多少?% gives the remainder after integer division. Use n % 2 == 0 to test if n is even.2。17 = 3 × 5 + 2。% 给出整除后的余数。用 n % 2 == 0 测试 n 是否为偶数。int(x) → truncates to integer. float(x) → converts to decimal. str(x) → converts to string. ON ICS3U A1.3; AB CSE1110 2.4.3.int(x) → 截断为整数。float(x) → 转换为小数。str(x) → 转换为字符串。ON ICS3U A1.3;AB CSE1110 2.4.3。int(7.9) return?int(7.9) 返回什么?int() truncates toward zero (drops the decimal). Use round(7.9) → 8 if you need rounding.7,不是 8。int() 向零截断(丢掉小数)。如果需要四舍五入,使用 round(7.9) → 8。student_age). Constants: UPPER_SNAKE_CASE (TAX_RATE). Constants should not change during the program. ON ICS3U A1.1; AB CSE1110 2.4.4.变量:蛇形命名法(student_age)。常量:全大写蛇形命名法(TAX_RATE)。常量在程序运行期间不应改变。ON ICS3U A1.1;AB CSE1110 2.4.4。TAX_RATE explains what 0.13 means. Prevents "magic number" bugs.一处更改 → 所有使用处更新。可读性:TAX_RATE 解释了 0.13 的含义。防止"魔法数字"错误。== != < > <= >=. BC CS10 Content: "relational operators." ON ICS3U A1.4.总是布尔值:True 或 False。六个运算符:== != < > <= >=。BC CS10 内容:"关系运算符。" ON ICS3U A1.4。"text" + 5). ValueError: right type, bad value (int("abc")). Know which error each mistake causes.TypeError:错误类型组合("文本" + 5)。ValueError:类型正确但值错误(int("abc"))。了解每种错误对应哪种失误。Practice Quiz综合测验
x = 5 then x = x * 2 then x = x - 3, what is the value of x?运行 x = 5,再 x = x * 2,再 x = x - 3 后,x 的值是什么?True in Python?Python 中 True 的数据类型是什么?True and False are the two values of the bool type. Note: in Python, bool is a subtype of int (True == 1, False == 0), but type(True) is bool.True 和 False 是 bool 类型的两个值。注意:在 Python 中,bool 是 int 的子类型(True == 1,False == 0),但 type(True) 是 bool。age = int(input("Age: "))?用户在提示时输入"25"。age = int(input("年龄:")) 的结果是什么?input() returns "25" (string). int("25") converts it to the integer 25. The combined call int(input(...)) stores a proper integer in age.input() 返回 "25"(字符串)。int("25") 将其转换为整数 25。组合调用 int(input(...)) 将一个真正的整数存储在 age 中。22 // 7 in Python?Python 中 22 // 7 的结果是什么?// is floor division: returns the integer quotient, rounding down (floor). 22 ÷ 7 = 3 remainder 1, so 22 // 7 = 3. Use 22 / 7 if you want the decimal result (≈3.142857).// 是整除:返回整数商,向下取整。22 ÷ 7 = 3 余 1,所以 22 // 7 = 3。如果需要小数结果(≈3.142857),使用 22 / 7。result = "Score: " + score where score = 88. What happens?学生写道 result = "分数:" + score,其中 score = 88。会发生什么?"Score: " + str(score) or f"Score: {score}". Forgetting str() is one of the top two beginner mistakes in this unit.Python 不会自动转换。修复:"分数:" + str(score) 或 f"分数:{score}"。忘记 str() 是本单元最常见的两大初学者错误之一。Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Explain what a variable is, and state the difference between assignment (
=) and equality test (==). Give an example of each. 🇺🇸 AP CSP AAP-1.A / AAP-1.B解释变量是什么,并说明赋值(=)和等式测试(==)的区别。各举一个例子。🇺🇸 AP CSP AAP-1.A / AAP-1.B - Name the four primitive data types (int, float, str, bool), give one example value for each, and state one real-world use case for each type. 🇨🇦 ON ICS3U A1.1 / AB CSE1110 2.4.3命名四种基本数据类型(整数、浮点数、字符串、布尔),为每种给出一个示例值,并为每种说明一个真实用途。🇨🇦 ON ICS3U A1.1 / AB CSE1110 2.4.3
- Trace a sequence of 5+ assignment statements to determine the final value of each variable. Verify by working step by step, not guessing. 🇺🇸 AP CSP AAP-1.B追踪 5 条以上的赋值语句序列,确定每个变量的最终值。通过逐步计算验证,而不是猜测。🇺🇸 AP CSP AAP-1.B
- Write a Python program that reads two numbers from the user and prints their sum, correctly wrapping
input()infloat(). 🇨🇦 ON ICS3U A2.1 / AB CSE1110 2.4.5编写一个 Python 程序,从用户读取两个数字并打印它们的和,正确地将input()用float()包装。🇨🇦 ON ICS3U A2.1 / AB CSE1110 2.4.5 - State what all seven arithmetic operators do (
+-*///%**) and give the result of17 // 5,17 % 5, and2 ** 8without a calculator. 🇨🇦 BC CS10 / AB CSE1110 2.4.6说明所有七个算术运算符的功能(+-*///%**),并在不用计算器的情况下给出17 // 5、17 % 5和2 ** 8的结果。🇨🇦 BC CS10 / AB CSE1110 2.4.6 - Explain what each of
int(),float(), andstr()does. State whatint(7.9)returns and why it is not 8. 🇨🇦 ON ICS3U A1.3 / AB CSE1110 2.4.3解释int()、float()和str()各自做什么。说明int(7.9)返回什么以及为什么不是 8。🇨🇦 ON ICS3U A1.3 / AB CSE1110 2.4.3 - State the Python naming conventions for variables (snake_case) and constants (UPPER_SNAKE_CASE), and explain why using a named constant is better than repeating a "magic number" throughout the code. 🇨🇦 ON ICS3U A1.1 / AB CSE1110 2.4.4说明 Python 变量(蛇形命名法)和常量(全大写蛇形命名法)的命名规范,并解释为什么使用具名常量优于在代码中重复"魔法数字"。🇨🇦 ON ICS3U A1.1 / AB CSE1110 2.4.4
- Write a complete Python program (BMI, temperature conversion, or similar) following the 5-step pipeline: IPO → pseudocode → Python → run with known input → name one edge case. 🇨🇦 AB CSE1110 2.4.1 / ON ICS3U A2.1按照五步流程编写一个完整的 Python 程序(BMI、温度转换或类似程序):IPO → 伪代码 → Python → 用已知输入运行 → 说明一个边界情况。🇨🇦 AB CSE1110 2.4.1 / ON ICS3U A2.1
- Explain what happens when a user types "abc" into a program that does
int(input(...)), and name the error type raised. 🇨🇦 BC CP11 / AB CSE1110 2.4.5解释当用户在执行int(input(...))的程序中输入"abc"时会发生什么,并命名所引发的错误类型。🇨🇦 BC CP11 / AB CSE1110 2.4.5 - State verbatim (or near-verbatim) CSTA 3A-AP-14 and AP CSP learning objective AAP-1.A, and explain how each relates to variables in programs. 🇺🇸 CSTA 3A / AP CSP逐字(或近逐字)陈述 CSTA 3A-AP-14 和 AP CSP 学习目标 AAP-1.A,并解释每个标准如何与程序中的变量相关。🇺🇸 CSTA 3A / AP CSP
- Honors: ICS4U A1.2 / A1.4 Explain widening vs narrowing type conversion. Give an example of integer overflow (Java context) and explain why
0.1 + 0.2 != 0.3in Python. 🇨🇦 ON ICS4U A1.2 / A1.4荣誉:ICS4U A1.2 / A1.4 解释扩宽与收窄类型转换。给出整数溢出的例子(Java 背景),并解释为什么 Python 中0.1 + 0.2 != 0.3。🇨🇦 ON ICS4U A1.2 / A1.4
What This Feeds Into本单元的去向
Programming fundamentals are the vocabulary every subsequent unit builds on. Variables, types, I/O, operators, conversion, and naming are assumed knowledge in Control Flow, Functions, Data Structures, and OOP. Both downstream AP courses depend on mastery of exactly this material. The link below points to the existing AP CSA guide, which uses statically-typed Java and therefore relies on the data-type and casting concepts taught here.编程基础是后续每个单元所依赖的词汇。变量、类型、输入/输出、运算符、转换和命名是控制流、函数、数据结构和面向对象编程的已知前提。两门下游 AP 课程都依赖本材料的掌握。以下链接指向现有 AP CSA 指南,该指南使用静态类型 Java,因此依赖这里所教授的数据类型和类型转换概念。
Within High School Computer Science.在 HS Computer Science 内部。
Unit 3 (Control Flow) takes the variables and assignment you learned here and adds if/else decisions and loops; you will use int and bool variables constantly. Unit 4 (Functions and Modular Design) formalises the five-step pipeline into reusable named blocks with parameters. Unit 5 (Data Structures) stores many values of the same type in lists and arrays; the data-type concepts from this guide apply to every element. Every later unit also uses input()/print() and the operator set taught here.第 3 单元(控制流)将你在这里学到的变量和赋值与 if/else 判断和循环结合,你将大量使用整数(int)和布尔(bool)变量。第 4 单元(函数与模块化设计)将五步流程正式化为带参数的可复用具名代码块。第 5 单元(数据结构)将同类型的多个值存储在列表和数组中,本指南的数据类型概念适用于每个元素。每个后续单元也都使用这里教授的 input()/print() 和运算符集。
AP feeder links (existing in this repo).AP 衔接链接(本仓库中已有)。
AP CSP Topics 3.1 (Variables and Assignments), 3.2 (Data Abstraction), and 3.3 (Mathematical Expressions) cover the material in this guide (Big Idea 3). AP CSA (Java) enforces static typing from line one: every variable must be declared with a type (int, double, String, boolean). Mastering data types, assignment, operators, and type conversion in Python here means the Java syntax is the only new layer to learn when you reach AP CSA.AP CSP 主题 3.1(变量与赋值)、3.2(数据抽象)和 3.3(数学表达式)涵盖本指南的内容(大概念 3)。AP CSA(Java)从第一行就强制执行静态类型:每个变量必须用类型声明(int、double、String、boolean)。在这里用 Python 掌握数据类型、赋值、运算符和类型转换,意味着当你学到 AP CSA 时,Java 语法是唯一需要学习的新层次。
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 are the main data types in programming?编程中主要的数据类型有哪些?
The core primitive types are int (whole numbers), float (decimals), string (text), and boolean (True or False). Every value you store belongs to one of these types, and choosing the right type for each piece of data is essential.核心的基本类型是 int(整数)、float(小数)、string(文本)和 boolean(True 或 False)。你存储的每个值都属于其中一种类型,为每项数据选对类型非常重要。
Why does input() always return a string in Python?为什么 Python 的 input() 总是返回字符串?
The input() function reads a line of text typed by the user and always returns it as a string, no matter what was typed. To do arithmetic with it you must convert it first, for example with int() or float().input() 函数读取用户输入的一行文本,无论输入什么都以字符串形式返回。如果要用它做算术运算,必须先转换,比如用 int() 或 float()。
What is the difference between arithmetic and relational operators?算术运算符和关系运算符有什么区别?
Arithmetic operators work on numbers and produce a number, such as addition or multiplication, while relational operators compare two values and return a boolean (True or False), such as greater than or equal to.算术运算符作用于数字并产生一个数字,比如加法或乘法;关系运算符比较两个值并返回布尔值(True 或 False),比如大于或等于。
Syllabus alignment & how to use this guide大纲对照与使用说明
How to use this guide如何使用本指南
Programming fundamentals are covered in every curriculum we map to. All four frameworks agree on the core building blocks: variables, data types (integer, float, string, boolean), input/output, and basic operators. Where they diverge is on type conversion depth: Ontario ICS4U strand A adds integer division, rounding, and the limitations of finite representation (a Grade-12 topic). Alberta CSE1110 names the full output-operator chain explicitly (outcomes 2.4.3–2.4.7). BC Computer Studies 10 lists all operators verbatim in its intro-constructs bullet. The table tells you which sections are core for you right now; each row cites the curriculum document it was checked against.编程基础在我们对照的所有大纲中均有涵盖。四套框架对核心构建块高度一致:变量(变量)、数据类型(整数、浮点数、字符串、布尔)、输入/输出和基本运算符。它们的分歧在于类型转换深度:安大略 ICS4U A 单元增加了整除、取整和有限表示局限(12 年级内容)。阿尔伯塔 CSE1110 明确列出了完整的输出运算符链(结果 2.4.3–2.4.7)。BC Computer Studies 10 在其初步构造条目中原文列出了所有运算符。下表告诉你当前哪些节属于你的核心;每行均注明所依据的课纲文件。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP | §1 through §7 in full. CSTA 3A-AP-14 (variables/lists), AP CSP AAP-1.A (represent a value with a variable), AAP-1.B (determine variable value after assignment), Topics 3.1, 3.2, 3.3 all map to this guide.§1 至 §7 完整学习。CSTA 3A-AP-14(变量/列表)、AP CSP AAP-1.A(用变量表示值)、AAP-1.B(确定赋值后变量值)、主题 3.1、3.2、3.3 均对应本指南。 | §5 type conversion depth (casting between Java types) is useful background for AP CSA; AP CSP floor needs only primitive-type casting.§5 类型转换深度(Java 类型之间的转换)对 AP CSA 是有益的背景;AP CSP 基础学生只需掌握基本类型转换。 | CSTA K-12 and AP CSP: CSTA 3A-AP-13, 3A-AP-14; AP CSP Big Idea 3 (AAP) AAP-1.A, AAP-1.B; topics 3.1, 3.2, 3.3:CSTA 3A-AP-13、3A-AP-14;AP CSP 大概念 3(AAP)AAP-1.A、AAP-1.B;主题 3.1、3.2、3.3 |
| 🇨🇦 ON Grade 11: ICS3U安大略 11 年级:ICS3U | §1 through §7 in full. ICS3U Strand A (A1.1, A1.3, A2.1) directly names constants, variables, integers, floats, strings, booleans, assignment statements, and programs with user input/output.§1 至 §7 完整学习。ICS3U A 单元(A1.1、A1.3、A2.1)直接点名常量、变量、整数、浮点数、字符串、布尔值、赋值语句和包含用户输入/输出的程序。 | Type conversion depth (§5 going-deeper) is ICS4U A1.2 (Grade 12); skip for ICS3U floor students.§5 深入中的类型转换深度属 ICS4U A1.2(12 年级),ICS3U 基础学生可跳过。 | ON/BC Computer Studies 11-12: ICS3U Strand A A1.1, A1.3, A2.1; ICS4U A1.1, A1.2, A1.4:ICS3U A 单元 A1.1、A1.3、A2.1;ICS4U A1.1、A1.2、A1.4 |
| 🇨🇦 BC: CS10 / CP11BC:CS10 / CP11 | §1 through §7. CS10 Content lists data types, constants and variables, arithmetic/relational/Boolean operators, and assignment operators verbatim. CP11 Content names "programming language constructs to support input/output, logic, decision structure, and loops."§1 至 §7。BC CS10 内容原文列出数据类型、常量与变量、算术/关系/布尔运算符和赋值运算符。CP11 内容点名"支持输入/输出、逻辑、判断结构和循环的编程语言构造"。 | BC has no explicit type-casting standard; §5 going-deeper is enrichment for BC students.BC 无明确类型转换标准;§5 深入对 BC 学生为拓展内容。 | ON/BC Computer Studies 11-12: CS10 intro-constructs Content bullet; CP11 "programming language constructs…" Content bullet:CS10 初步构造内容条目;CP11"编程语言构造……"内容条目 |
| 🇨🇦 AB: CSE1110阿尔伯塔:CSE1110 | §1 through §7. CSE1110 outcomes 2.4.3–2.4.7 explicitly name data types (integers, reals, characters, strings), variables, constants, input commands, assignment/arithmetic operators, and output commands: a near-perfect match for this guide.§1 至 §7。CSE1110 结果 2.4.3–2.4.7 明确点名数据类型(整数、实数、字符、字符串)、变量、常量、输入命令、赋值/算术运算符和输出命令:与本指南高度契合。 | Advanced type representation (§5 going-deeper) is CSE1120+ territory; skip for CSE1110 floor students.高级类型表示(§5 深入)属 CSE1120+ 范畴,CSE1110 基础学生可跳过。 | Alberta CTS Computing Science: CSE1110 outcomes 2.4.3–2.4.7:CSE1110 结果 2.4.3–2.4.7 |
| 🇺🇸 AP CSP / AP CSA feeder trackAP CSP / AP CSA 衔接轨道 | All seven sections including going-deeper boxes. AP CSP Topics 3.1–3.3 (variables, data abstraction, expressions) and AP CSA (Java: typed variables, casting, I/O) both depend on mastery of this unit.全部 7 节,包含深入框。AP CSP 主题 3.1–3.3(变量、数据抽象、表达式)和 AP CSA(Java:类型化变量、类型转换、I/O)都依赖本单元的掌握。 | Nothing: this unit is the prerequisite vocabulary that both AP CS courses assume. See the feeder links in "What This Feeds Into."无:本单元是两门 AP CS 课程所假设的前置词汇。见"本单元的去向"中的衔接链接。 | CSTA K-12 and AP CSP: AP CSP Big Idea 3 (AAP) topics 3.1 Variables and Assignments, 3.2 Data Abstraction, 3.3 Mathematical Expressions:AP CSP 大概念 3(AAP)主题 3.1 变量与赋值、3.2 数据抽象、3.3 数学表达式 |
Once you have located your row, use the two cards below for the speed at which you should work through the recommended sections.找到所在行后,用下面两张卡片决定推进速度。
Memorise four things: what a variable is and how assignment works (x = 5 stores 5, x == 5 tests equality); the four primitive data types (int, float, string, boolean) and one example of each; how to call input() and print() in Python; and the order-of-operations rule (PEMDAS). Read every cram-cheat box. Skip the going-deeper type-conversion sections.背熟四件事:变量是什么以及赋值如何工作(x = 5 存储 5,x == 5 测试相等);四种基本数据类型(整数、浮点数、字符串、布尔)及各一个例子;如何在 Python 中调用 input() 和 print();以及运算优先级规则(PEMDAS)。读每个速记框,跳过深入的类型转换部分。
Always declare your types explicitly and convert deliberately. AP CSP Topics 3.1–3.3 test whether you can predict the value of a variable after a sequence of assignment statements. ON ICS3U A1.1 and AB CSE1110 2.4.3–2.4.7 require you to use the correct data type for each piece of data: §2 and §5 show you the rules. For AP CSA: Java is statically typed, so §5 type casting is useful background from Unit 1 (Using Objects and Methods) of that course onward.始终显式声明类型并有意识地转换。AP CSP 主题 3.1–3.3 测试你是否能在一系列赋值语句后预测变量的值。ON ICS3U A1.1 和 AB CSE1110 2.4.3–2.4.7 要求你为每条数据使用正确的数据类型:§2 和 §5 展示了相关规则。对于 AP CSA:Java 是静态类型语言,因此从该课程第 1 单元(使用对象和方法)起,§5 的类型转换就是有用的背景知识。
int(), float(), str()) and the idea that data changes meaning when its type changes. The Honors chip marks the going-deeper box where integer overflow, floating-point precision limits, and widening/narrowing casts (Java style) are introduced. That box maps to Ontario ICS4U A1.2/A1.4 (Grade 12) and Alberta CSE1120 (Structured Programming 2). For ICS3U / CSE1110 / AP CSP floor students, the three Python conversion functions in the cram box are the assessed level.§5(类型转换)介绍了显式转换函数(int()、float()、str()),以及数据类型改变时含义也随之改变的概念。Honors 标记深入框,其中引入整数溢出、浮点精度限制和扩宽/收窄转换(Java 风格)。该框对应安大略 ICS4U A1.2/A1.4(12 年级)和阿尔伯塔 CSE1120(结构化编程 2)。对于 ICS3U / CSE1110 / AP CSP 基础学生,速记框中的三个 Python 转换函数是被评估的层次。