High School Computer Science

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 全程并排,让你在每节结束后都能编写、阅读并解释真正可运行的代码。学完后,你将编写并运行第一个完整程序,并准确理解每一行的含义。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Pseudocode + Python worked examples伪代码 + Python 例题

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 in inheritance) is AP CSA territory; AP CSP floor needs only primitive-type casting.§5 类型转换深度(继承中的类型转换)属 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.找到所在行后,用下面两张卡片决定推进速度。

!
If you are cramming the night before如果你在临阵磨枪

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)。读每个速记框,跳过深入的类型转换部分。

*
If you are going for the top mark如果你目标顶分

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 directly assessed from Unit 1 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 的类型转换。

Type conversion note.类型转换说明。 Section 5 (Type Conversion and Casting) introduces explicit conversion functions (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 转换函数是被评估的层次。

Variables and Assignment变量与赋值

Three facts — memorise before anything else.三个要点 — 最先背会这些。
  • 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 = 5 puts 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。混淆两者是最常见的初学者错误。
Key idea: after each assignment, the variable holds exactly one value. The right-hand side is evaluated first using the current state of all variables, then the result is stored in the left-hand side. So 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:"使用适当的变量和常量保存数据。"
WE
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 = 10b = 20,交换它们的值,使操作后 a == 20b == 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.元组解包方式在任何赋值之前就对两侧求值,因此不需要临时变量。两种方式产生相同结果。

After these lines run, what is the value of y?
x = 3
y = x + 4
x = 10
这几行运行后,y 的值是什么?
x = 3
y = x + 4
x = 10
§1 · Q1
10
14
7
3
Line 2 sets y = x + 4 = 3 + 4 = 7 using x's value at that moment. Line 3 then changes x to 10, but y has already been set and does not update automatically. y stays 7.第 2 行用 x 此时的值设置 y = x + 4 = 3 + 4 = 7。第 3 行再将 x 改为 10,但 y 已经被设置,不会自动更新。y 保持为 7。
Assignment captures the value at the moment it runs. Changing x afterwards does not retroactively change y. y = 3 + 4 = 7.赋值捕获运行时刻的值。之后更改 x 不会追溯改变 y。y = 3 + 4 = 7。
Which line correctly increases the value of score by 10?哪行代码能正确地将 score 的值增加 10?
§1 · Q2
score == score + 10
score = score + 10
score + 10 = score
10 + score
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 但不存储任何内容的比较。
Only single = 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 = score10 + 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数据类型:整数、浮点数、字符串、布尔

Four primitive types — know each by example.四种基本类型 — 用例子记住每种。
  • intint(整数) — whole numbers, positive or negative. Examples: 42, -7, 0. Use for counts, indices, ages.— 正负整数。例:42-70。用于计数、索引、年龄。
  • floatfloat(浮点数) — numbers with a decimal point. Examples: 3.14, -0.5, 2.0. Use for measurements, prices, scientific values.— 含小数点的数。例:3.14-0.52.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: True or False. 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:"正确使用常量和变量,包括整数、浮点数、字符串和布尔值。"
Critical trap: "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:"使用适当的数据类型,如整数、实数、字符和字符串。"
WE
Worked Example 2 · Declaring and inspecting types例题 2 · 声明并检查类型

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;)。

What is the data type of "3.14" (with quotes) in Python?在 Python 中,"3.14"(带引号)的数据类型是什么?
§2 · Q1
str (string)str(字符串)
floatfloat(浮点数)
int (integer)int(整数)
bool (boolean)bool(布尔)
Quotation marks always make a string, regardless of what is inside. "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。不能直接对它进行算术运算。
Quotes = string. Without quotes, 3.14 would be a float. The decimal point alone does not determine the type; the presence or absence of quotes does.引号 = 字符串。没有引号,3.14 才是浮点数。小数点本身不决定类型;是否有引号才决定类型。
Which data type is best for storing whether a student has submitted their assignment?哪种数据类型最适合存储学生是否已提交作业?
§2 · Q2
int整数 (int)
float浮点数 (float)
str字符串 (str)
bool布尔 (bool)
A boolean (bool) has exactly two values: True or False. "Has the student submitted?" is a yes/no question, so bool is the correct type. Using an integer (0/1) works but is less expressive and more error-prone.布尔(bool)只有两个值:True 或 False。"学生是否已提交?"是一个是/否问题,所以 bool 是正确类型。使用整数(0/1)可行,但表达力较差且更容易出错。
Yes/no conditions use bool. int is for counting; float for decimals; str for text. "submitted = True" reads clearly and cannot be accidentally set to 2 the way an int could.是/否条件使用 bool。int 用于计数;float 用于小数;str 用于文本。"submitted = True" 读起来清晰,且不像 int 那样可能被意外设为 2。
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 = 17age = "seventeen" 是合法的(尽管是不良实践)。AP CSA(Java)从第 1 单元就要求静态类型声明;本指南的 Python 示例可直接迁移,因为底层类型概念相同——只是声明语法不同。ON ICS4U A1.4 增加了有限表示局限的概念:Java 中的 int 最多保存 2,147,483,647(2³¹ − 1);超出则导致整数溢出,一种无声的逻辑错误。Python 整数没有大小限制(任意精度),这就是为什么溢出不是 Python 初学者需要关心的问题。


Input and Output输入与输出

Two Python functions to know cold.必须熟记的两个 Python 函数。
  • 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:"使用输出命令……显示已处理数据。"
Critical: 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:"使用字面量和输入命令……提供待处理数据。"
WE
Worked Example 3 · Area of a rectangle例题 3 · 矩形面积

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。始终选择与用户实际可能输入相匹配的转换。

A student writes: n = input("Enter a number: ") then result = n * 2. If the user types 5, what is result?一名学生写道:n = input("输入一个数字:") 然后 result = n * 2。如果用户输入 5,result 是什么?
§3 · Q1
10
A TypeError (cannot multiply)TypeError(无法相乘)
"55"
5
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() 转换。
Which line correctly reads an integer from the user into variable age?哪行代码能正确地从用户读取整数到变量 age
§3 · Q2
age = input("Age: ")
age = int(input("Age: "))
age = print(input("Age: "))
age = float(input("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)。
input() always returns a string. To get an int, wrap it: int(input(...)). Never assign print()'s return value — print returns None.input() 总是返回字符串。要得到整数,需要包装:int(input(...))。永远不要赋值 print() 的返回值——print 返回 None。

Operators: Arithmetic and Relational运算符:算术与关系

Arithmetic operators (work on numbers) and relational operators (return bool).算术运算符(作用于数字)与关系运算符(返回布尔值)。
  • 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 return True or False. ON ICS3U A1.4 names all six. BC CS10 Content (verbatim): "assignment and relational operators."== 等于,!= 不等于,< 小于,> 大于,<= 小于等于,>= 大于等于。总是返回 TrueFalse。ON ICS3U A1.4 列出所有六种。BC CS10 内容(原文):"赋值与关系运算符。"
  • PEMDAS / BODMAS order:运算优先级(PEMDAS/BODMAS): Parentheses → Exponents → Multiply/Divide → Add/Subtract. When in doubt, add parentheses.括号 → 指数 → 乘/除 → 加/减。有疑问时,加括号。
WE
Worked Example 4 · Operator results table例题 4 · 运算符结果表

Trace each expression given a = 17 and b = 5.给定 a = 17b = 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 toward zero). 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)等问题至关重要。

What is the value of 10 % 3 in Python?Python 中 10 % 3 的值是多少?
§4 · Q1
3
3.33
1
0
% 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 是偶数。
% gives the remainder after integer division. 10 ÷ 3 = 3 remainder 1. So 10 % 3 = 1.% 给出整除后的余数。10 ÷ 3 = 3 余 1。所以 10 % 3 = 1。
Which expression evaluates to True if x = 8?x = 8 时,哪个表达式结果为 True
§4 · Q2
x % 2 == 0
x > 10
x == 9
x != 8
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。
8 % 2 = 0, so 8 % 2 == 0 is True. All other options are False when x = 8.8 % 2 = 0,所以 8 % 2 == 0 为 True。当 x = 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类型转换与强制转换

Three conversion functions to memorise.三个必记的转换函数。
  • 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")42int("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.0float("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)
ON ICS3U A1.3 requires "use assignment statements correctly with both arithmetic and string expressions" — type conversion is the bridge. AB CSE1110 outcome 2.4.3 requires using "appropriate data types."ON ICS3U A1.3 要求"正确使用包含算术和字符串表达式的赋值语句"——类型转换是桥梁。AB CSE1110 结果 2.4.3 要求使用"适当的数据类型"。
WE
Worked Example 5 · Conversion errors and fixes例题 5 · 转换错误与修复

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。类型错误是最常见的初学者错误之一——一旦你理解了错误消息的含义,也是最容易修复的。

What does int(7.9) return in Python?Python 中 int(7.9) 返回什么?
§5 · Q1
8
7
7.9
ValueErrorValueError
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()
int() truncates (drops the decimal), it does NOT round. 7.9 becomes 7, not 8.int() 截断(丢掉小数),不四舍五入。7.9 变为 7,不是 8。
A student writes result = "Total: " + 42. What happens?一名学生写道 result = "总计:" + 42。会发生什么?
§5 · Q2
result = "Total: 42"result = "总计:42"
result = "Total: " (42 is ignored)result = "总计:"(42 被忽略)
result = 42result = 42
TypeError — cannot concatenate str and intTypeError——无法拼接字符串和整数
Python does not automatically convert the integer to a string. Adding a str and an int raises TypeError. Fix: "Total: " + str(42) or f"Total: {42}".Python 不会自动将整数转换为字符串。将字符串和整数相加会引发 TypeError。修复:"总计:" + str(42)f"总计:{42}"
Python never silently converts between str and int. You must explicitly call str(42) to concatenate. Otherwise: TypeError.Python 从不在字符串和整数之间悄悄转换。必须显式调用 str(42) 才能拼接。否则:TypeError。
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 destination type can represent every value the source can. 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——目标类型可以表示源类型的所有值。收窄: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常量与命名规范

Good names make code readable. Three rules.好名称使代码可读。三条规则。
  • 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_nametotal_scorecalculate_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's final), 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.13MAX_SCORE = 100。Python 没有真正的常量关键字(不像 Java 的 final),但该约定传达了意图。ON ICS3U A1.1:"在计算机程序中正确使用常量……" AB CSE1110 2.4.4:"使用适当的变量和常量保存数据。"
  • Descriptive over short描述性优先于简短 width beats w; student_age beats a. The exception: loop counters i, j, k are universally understood. AB CSE1110 outcome 2.4.2: "use appropriate internal and external documentation."width 优于 wstudent_age 优于 a。例外:循环计数器 ijk 是公认的。AB CSE1110 结果 2.4.2:"使用适当的内部和外部文档。"
WE
Worked Example 6 · Refactoring with constants and clear names例题 6 · 用常量和清晰命名重构代码

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),所有计算自动更新。这就是常量比样式更重要的原因——它们防止了"改一处、漏十处"的错误。

Which variable name follows Python's snake_case convention and is most descriptive?哪个变量名遵循 Python 的蛇形命名规范且最具描述性?
§6 · Q1
StudentAge
sa
student_age
STUDENT_AGE
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 保留给常量。
Python convention: variables/functions → snake_case. Classes → PascalCase. Constants → UPPER_SNAKE_CASE. Cryptic abbreviations should be avoided.Python 约定:变量/函数 → 蛇形命名法。类 → 帕斯卡命名法。常量 → 全大写蛇形命名法。应避免难懂的缩写。
Why is it better to write MAX_STUDENTS = 30 than to use the number 30 directly throughout the code?为什么写 MAX_STUDENTS = 30 比在代码中直接使用数字 30 更好?
§6 · Q2
If the value needs to change, you update it in one place and all uses update automatically如果值需要更改,只在一处更新,所有使用处自动更新
It makes the program run faster它使程序运行更快
Python requires all numbers to be namedPython 要求所有数字都必须命名
It converts 30 to a different data type它将 30 转换为不同的数据类型
Using a named constant means you change the value in exactly one place. If you use the literal 30 in 15 places and the class size changes to 32, you have to find and change 15 occurrences — and risk missing one. A named constant also documents what the number means.使用具名常量意味着只在一处更改值。如果你在 15 处使用字面值 30 而班级规模变为 32,你必须找到并更改 15 处——还有漏掉一处的风险。具名常量还能说明数字的含义。
Constants are about maintainability and readability, not speed or type conversion. Python does not require naming numbers — it's a best-practice convention.常量关乎可维护性和可读性,与速度或类型转换无关。Python 不要求为数字命名——这是最佳实践约定。

Writing and Running Your First Program编写并运行你的第一个程序

Five steps from blank file to running program.从空白文件到运行程序的五个步骤。
  • 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 结构。"
WE
Worked Example 7 · BMI calculator — full pipeline例题 7 · 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("包含用户输入、处理和屏幕输出")所要求的。

In the five-step pipeline, what should come immediately after writing pseudocode?在五步流程中,写完伪代码后紧接着应该做什么?
§7 · Q1
Translate each pseudocode line into Python将每行伪代码翻译成 Python
Run the program with edge-case inputs用边界情况输入运行程序
Choose a programming language选择编程语言
Show the program to a classmate将程序展示给同学
The five-step pipeline is: (1) IPO, (2) pseudocode, (3) Python translation, (4) run with known input, (5) edge-case testing. After pseudocode comes translation. Running and edge-case testing come later.五步流程是:(1) IPO,(2) 伪代码,(3) Python 翻译,(4) 用已知输入运行,(5) 边界情况测试。伪代码之后是翻译。运行和边界情况测试在之后进行。
Order: IPO → pseudocode → Python translation → run with known input → edge cases. Skipping straight to edge cases before you have working Python code wastes time.顺序:IPO → 伪代码 → Python 翻译 → 用已知输入运行 → 边界情况。在有可运行 Python 代码之前直接进行边界情况测试会浪费时间。
A program asks for the user's age with 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 时会发生什么?
§7 · Q2
next_year = "abc1"next_year = "abc1"
next_year = 1next_year = 1
TypeError — cannot add str and intTypeError——无法将字符串和整数相加
The program skips the line silently程序静默跳过该行
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。两者都是需要处理的边界情况。
input() returns a string. Strings and ints cannot be added in Python — TypeError. Python never silently converts or skips type errors.input() 返回字符串。字符串和整数在 Python 中不能相加——TypeError。Python 从不悄悄转换或跳过类型错误。
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.99f"数量:{count:,}"数量:1,234,567。BC CP11 内容(原文):"支持输入/输出的编程语言构造"和"将设计规格转化为源代码"——格式化输出是该翻译的核心部分。AB CSE1110 2.4.7 要求使用"输出命令……显示已处理数据"——f 字符串是 Python 中最具可读性的实现方式。


Exam Strategy and Common Pitfalls考试策略与常见陷阱

Discipline before you write a single line写下第一行之前的纪律
  • 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.= 赋值。== 比较。/ 给出浮点数。// 给出整数。% 给出余数。混淆这些是本单元逻辑错误的主要来源。
Variables, types, and conversion questions (§1-§5)变量、类型与转换问题(§1-§5)
  • 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 exam, when asked "what is the result of …", always state the type first: "a string, '42'" or "an integer, 3". Examiners often award the type point separately from the value point.在笔试中,当被问到"……的结果是什么"时,始终先说类型:"字符串 '42'"或"整数 3"。考官通常将类型分和值分分开评分。
Constants, naming, and first programs (§6-§7)常量、命名与第一个程序(§6-§7)
  • Name the convention.说出命名规范。 When asked about naming in Python: variables/functions use snake_case; constants use UPPER_SNAKE_CASE; classes use PascalCase. One mark per convention on many marking schemes.被问到 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 is worth marks in ON ICS3U A2.1 and AB CSE1110 2.4.1 contexts.对你编写的每个程序,在心里测试:如果用户输入 0 会怎样?负数?非数字字符串?发现并陈述这些在 ON ICS3U A2.1 和 AB CSE1110 2.4.1 背景下值得得分。
Answer hygiene作答规范
  • Use AP CSP pseudocode on AP CSP exams.在 AP CSP 考试中使用 AP CSP 伪代码。 AP CSP uses its own keyword set: assignment is , display is DISPLAY(), Boolean values are TRUE/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(...)) or float(input(...)) in full — never just input(). Leaving out the conversion is a mark-losing error on every curriculum that assesses I/O.如果你的解决方案需要读取数字,完整写出 int(input(...))float(input(...))——永远不要只写 input()。遗漏转换在所有评估 I/O 的课程中都是失分错误。

Flashcards闪卡

0 / 14 flipped0 / 14 已翻
What is a variable?什么是变量?
A named storage location in memory that holds one value. The name is chosen by the programmer. AP CSP AAP-1.A.内存中保存一个值的具名存储位置。名称由程序员选择。AP CSP AAP-1.A。
Assignment vs equality赋值 vs 等式
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。
Four primitive data types四种基本数据类型
int: whole numbers. float: decimals. str: quoted text. bool: True or False. ON ICS3U A1.1.int(整数):整数。float(浮点数):小数。str(字符串):带引号的文本。bool(布尔):True 或 False。ON ICS3U A1.1。
Type of "42"?"42" 的类型?
str (string). Quotes always make a string, regardless of content. "42"42 (int). Cannot do arithmetic on "42" directly.str(字符串)。引号总是创建字符串,无论内容是什么。"42"42(整数)。不能直接对 "42" 进行算术运算。
What does input() return?input() 返回什么?
Always a str (string), regardless of what the user types. Convert immediately: int(input(...)) or float(input(...)). AB CSE1110 2.4.5.总是字符串(str),无论用户输入什么。立即转换:int(input(...))float(input(...))。AB CSE1110 2.4.5。
Arithmetic operators算术运算符
+ add · - subtract · * multiply · / true divide (float) · // floor divide (int) · % remainder · ** power. BC CS10 Content.+ 加 · - 减 · * 乘 · / 真除(浮点数)· // 整除(整数)· % 余数 · ** 幂。BC CS10 内容。
What is 17 % 5?17 % 5 等于多少?
2. 17 = 3 × 5 + 2. % 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 是否为偶数。
Three type conversion functions三个类型转换函数
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。
What does int(7.9) return?int(7.9) 返回什么?
7 — not 8. int() truncates toward zero (drops the decimal). Use round(7.9) → 8 if you need rounding.7——不是 8。int() 向零截断(丢掉小数)。如果需要四舍五入,使用 round(7.9) → 8。
Naming: variable vs constant命名:变量 vs 常量
Variables: snake_case (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。
Why use named constants?为什么使用具名常量?
Change in one place → all uses update. Readable: TAX_RATE explains what 0.13 means. Prevents "magic number" bugs.一处更改 → 所有使用处更新。可读性:TAX_RATE 解释了 0.13 的含义。防止"魔法数字"错误。
Five-step first program pipeline编写第一个程序的五步流程
1 IPO → 2 Pseudocode → 3 Python translation → 4 Run with known input → 5 Edge-case testing. AB CSE1110 2.4.1; ON ICS3U A2.1.1 IPO → 2 伪代码 → 3 Python 翻译 → 4 用已知输入运行 → 5 边界情况测试。AB CSE1110 2.4.1;ON ICS3U A2.1。
Relational operators — what do they return?关系运算符——返回什么?
Always bool: True or False. Six operators: == != < > <= >=. BC CS10 Content: "relational operators." ON ICS3U A1.4.总是布尔值:True 或 False。六个运算符:== != < > <= >=。BC CS10 内容:"关系运算符。" ON ICS3U A1.4。
TypeError vs ValueErrorTypeError vs ValueError
TypeError: wrong types combined ("text" + 5). ValueError: right type, bad value (int("abc")). Know which error each mistake causes.TypeError:错误类型组合("文本" + 5)。ValueError:类型正确但值错误(int("abc"))。了解每种错误对应哪种失误。

Practice Quiz综合测验

After running 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 的值是什么?
Q1
7
10
7
2
Trace: x = 5 → x = 5 * 2 = 10 → x = 10 - 3 = 7. Each assignment replaces the old value.追踪:x = 5 → x = 5 * 2 = 10 → x = 10 - 3 = 7。每次赋值替换旧值。
Step 1: x = 5. Step 2: x = 10. Step 3: x = 7. Trace line by line — each assignment uses the current value.步骤 1:x = 5。步骤 2:x = 10。步骤 3:x = 7。逐行追踪——每次赋值使用当前值。
What is the data type of True in Python?Python 中 True 的数据类型是什么?
Q2
bool (boolean)bool(布尔)
str (string)str(字符串)
int (integer)int(整数)
floatfloat(浮点数)
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.TrueFalse 是 bool 类型的两个值。注意:在 Python 中,bool 是 int 的子类型(True == 1False == 0),但 type(True) 是 bool。
True and False are bool. They are not strings ("True" with quotes would be str). ON ICS3U A1.1 lists boolean as a core data type.True 和 False 是 bool。它们不是字符串(带引号的 "True" 才是 str)。ON ICS3U A1.1 将布尔列为核心数据类型。
A user enters "25" when prompted. What is the result of age = int(input("Age: "))?用户在提示时输入"25"。age = int(input("年龄:")) 的结果是什么?
Q3
The string "25"字符串 "25"
The integer 25整数 25
The float 25.0浮点数 25.0
ValueErrorValueError
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 中。
int() converts "25" (string) to 25 (integer). No float, no error — "25" is a valid integer string.int() 将 "25"(字符串)转换为 25(整数)。没有浮点数,没有错误——"25" 是有效的整数字符串。
What is the result of 22 // 7 in Python?Python 中 22 // 7 的结果是什么?
Q4
3.14
3.142857
1
3
// is floor division — returns the integer quotient, truncating toward zero. 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
// gives the integer quotient. / gives the float quotient. 22 // 7 = 3 (not 3.14...).// 给出整数商。/ 给出浮点商。22 // 7 = 3(不是 3.14...)。
A student writes result = "Score: " + score where score = 88. What happens?学生写道 result = "分数:" + score,其中 score = 88。会发生什么?
Q5
TypeError — cannot concatenate str and intTypeError——无法拼接字符串和整数
result = "Score: 88"result = "分数:88"
result = 88result = 88
result = "Score: " (88 dropped)result = "分数:"(88 被丢弃)
Python does not auto-convert. Fix: "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() 是本单元最常见的两大初学者错误之一。
str + int raises TypeError in Python. You must explicitly call str() on the integer before concatenating.Python 中字符串 + 整数会引发 TypeError。必须在拼接之前显式对整数调用 str()。
Which line follows the correct Python naming convention for a constant holding the speed of light?哪行代码遵循正确的 Python 命名规范来定义保存光速的常量?
Q6
speedOfLight = 299792458
speed_of_light = 299792458
SPEED_OF_LIGHT = 299792458
SpeedOfLight = 299792458
Constants use UPPER_SNAKE_CASE in Python. Option A is camelCase (JS style). Option B is snake_case (correct for variables). Option D is PascalCase (for classes).Python 中常量使用全大写蛇形命名法。选项 A 是驼峰命名法(JS 风格)。选项 B 是蛇形命名法(变量的正确格式)。选项 D 是帕斯卡命名法(用于类)。
Python conventions: UPPER_SNAKE_CASE = constant; snake_case = variable or function; PascalCase = class. ON ICS3U A1.1; AB CSE1110 2.4.4.Python 约定:UPPER_SNAKE_CASE = 常量;snake_case = 变量或函数;PascalCase = 类。ON ICS3U A1.1;AB CSE1110 2.4.4。
Which CSTA standard at Level 3A specifically addresses variables? 🇺🇸 CSTA3A 级别哪个 CSTA 标准专门涉及变量?🇺🇸 CSTA
Q7
3A-AP-13
3A-AP-14
3A-AP-17
3A-DA-09
CSTA 3A-AP-14 (verbatim): "Use lists to simplify solutions, generalizing computational problems instead of repeatedly using simple variables." This is the HS-level variable/list standard. Variables are introduced at Level 2 (2-AP-11).CSTA 3A-AP-14(原文):"使用列表简化解决方案,将计算问题泛化而非重复使用简单变量。"这是 HS 级别的变量/列表标准。变量在 Level 2(2-AP-11)引入。
3A-AP-13 = prototypes using algorithms. 3A-AP-14 = variables/lists (this unit). 3A-AP-17 = decomposition (Unit 1). 3A-DA-09 = bit representations.3A-AP-13 = 使用算法的原型。3A-AP-14 = 变量/列表(本单元)。3A-AP-17 = 分解(第 1 单元)。3A-DA-09 = 位表示。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

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 CSA Unit 1 · Using Objects and Methods (Java requires explicit type declarations and casting — the data-type and conversion concepts from this guide are assumed from day one)AP CSA Unit 1 · 使用对象和方法(Java 需要显式类型声明和类型转换——本指南的数据类型和转换概念从第一天起就被假设已知)

AP CSP Topics 3.1 (Variables and Assignments), 3.2 (Data Abstraction), and 3.3 (Mathematical Expressions) directly test the material in this guide — they cover roughly 30–35% of the AP CSP exam through 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 CSP 考试 30–35%。AP CSA(Java)从第一行就强制执行静态类型:每个变量必须用类型声明(intdoubleStringboolean)。在这里用 Python 掌握数据类型、赋值、运算符和类型转换,意味着当你学到 AP CSA 时,Java 语法是唯一需要学习的新层次。