📚 Programming Fundamentals: Variables, Data Types and Control Structures | 编程基础:变量、数据类型与控制结构
In Edexcel A Level Computer Science, the 'Programming' topic focuses on the building blocks needed to design and write reliable programs. This article summarises variables, data types, control structures, subroutines and recursion, with clear links to pseudocode and the assessment objectives, and adds the extra detail you need to answer exam questions with confidence.
在 Edexcel A Level 计算机科学中,"编程"主题聚焦于设计和编写可靠程序所需的基础构件。本文总结变量、数据类型、控制结构、子程序与递归,并结合伪代码与考核目标进行讲解,同时补充考试作答所需的细节,帮助你更有把握地回答问题。
1. Variables and Constants | 变量与常量
In programming, a variable is a named location in memory that stores a value. The value can be read, updated, or used in expressions. Most languages require a variable to be declared before use, and some require an explicit data type.
在编程中,变量是内存中命名的存储位置,用于保存数值。该值可以被读取、更新或用于表达式。大多数语言要求变量在使用前声明,有些语言还要求明确指定数据类型。
A constant is a value that remains unchanged throughout the execution of a program. In pseudocode, constants are often declared using the keyword CONST. They help avoid 'magic numbers' in code, so a reader can see immediately what a value means.
常量是在程序执行过程中保持不变的值。在伪代码中,常量通常使用关键字 CONST 声明。它们有助于避免代码中出现"魔法数字",让读者一眼就能看出该数值的含义。
Assignment is the act of giving a variable a value, and in pseudocode it is written with a left arrow, for example counter ← 0. Assignment always replaces the previous contents of the variable, whereas a comparison such as counter = 0 only tests a condition and never changes any stored value.
赋值是把一个值放入变量的操作,在伪代码中写作左箭头,例如 counter ← 0。赋值总是覆盖变量原有的内容,而像 counter = 0 这样的比较只测试条件,不会改变任何已存储的值。
- Variables are mutable; constants are immutable. | 变量可变;常量不可变。
- Always initialise variables before reading them. | 读取变量前务必先初始化。
- Use meaningful names such as customerAge rather than x. | 使用有意义的名称,如 customerAge,而不是 x。
- Declare a constant once so a single edit updates every use. | 常量只声明一次,修改一处即可更新所有使用位置。
Choosing good identifiers matters because programs are read far more often than they are written. A well-named variable documents itself, reduces the chance of confusing two similar values, and makes a trace table far easier to follow during an exam.
选择好的标识符很重要,因为程序被阅读的次数远多于被编写的次数。命名良好的变量本身就是文档,可以降低混淆两个相似数值的风险,也让考试时的追踪表更易读。
2. Primitive Data Types | 原始数据类型
Primitive data types are the basic categories of value that a programming language provides. The most common types are integer, real (floating-point), Boolean, and character.
原始数据类型是编程语言提供的基本值类别。最常见的类型有整型、实数型(浮点型)、布尔型和字符型。
Each type uses a different amount of memory and supports different operations. For example, integers support whole-number arithmetic, while reals support fractional arithmetic, and Booleans support logical operations such as AND, OR and NOT.
每种类型占用不同的内存并支持不同的操作。例如,整型支持整数运算,而实数型支持小数运算,布尔型则支持 AND、OR、NOT 等逻辑运算。
| Data type | 中文名称 | Example values | Typical use |
|---|---|---|---|
| Integer | 整型 | 0, 42, −17 | Counters, indices, whole quantities |
| Real / Float | 实数型 / 浮点型 | 3.14, −0.5, 2.0 | Measurements, averages, money |
| Boolean | 布尔型 | TRUE, FALSE | Flags, conditions, loop control |
| Character | 字符型 | 'A', '7', '?' | Single symbols, text processing |
| String | 字符串 | "Hao", "A Level" | Names, messages, records of text |
A character is stored as a numeric code, for example using ASCII or Unicode. This is why ASC('A') returns 65 and CHR(65) returns 'A', and it is the reason characters can be compared and sorted alphabetically.
字符以数字编码形式存储,例如使用 ASCII 或 Unicode。这就是 ASC('A') 返回 65、CHR(65) 返回 'A' 的原因,也是字符能够按字母顺序比较和排序的原因。
Two limitations are worth remembering. Integers have a fixed range, so a value that is too large causes overflow. Reals are stored in binary floating point, so some decimal values cannot be represented exactly and rounding errors accumulate if you add them many times.
有两点局限值得记住。整型的取值范围是固定的,数值过大就会发生溢出。实数以二进制浮点形式存储,因此某些十进制值无法精确表示,若反复相加,舍入误差会不断累积。
3. Operators and Expressions | 运算符与表达式
An expression is a combination of values, variables and operators that produces a new value. Operators fall into three families: arithmetic, relational (comparison) and Boolean (logical).
表达式是由值、变量和运算符组合而成并产生新值的结构。运算符可分为三类:算术运算符、关系运算符(比较)和布尔运算符(逻辑)。
| Family | 中文类别 | Operators |
|---|---|---|
| Arithmetic | 算术 | + − × ÷ MOD DIV ^ |
| Relational | 关系 | = ≠ < > ≤ ≥ |
| Boolean | 布尔 | AND OR NOT |
3 and 17 MOD 5 = 2. A common use of MOD is testing whether a number is even: n MOD 2 = 0.
整除与取模是高频考点。DIV 返回除法的整数部分,MOD 返回余数,因此 17 DIV 5 = 3,17 MOD 5 = 2。MOD 的一个常见用途是判断奇偶:n MOD 2 = 0 表示偶数。
Evaluation follows a fixed precedence, and the safest exam habit is to bracket anything ambiguous. A useful memory aid is: brackets first, then NOT, then AND, then OR, with arithmetic evaluated before comparison.
求值遵循固定的优先级,考试中最稳妥的做法是给任何有歧义的表达式加括号。一个实用的记忆顺序是:先括号,再 NOT,然后 AND,最后 OR,而算术运算先于比较运算求值。
( ) → NOT → × ÷ MOD DIV → + − → = ≠ < > ≤ ≥ → AND → OR
4. Strings, Casting and Type Checking | 字符串、类型转换与类型检查
Strings are handled with built-in operations rather than arithmetic. Typical pseudocode functions include LENGTH, SUBSTRING, LEFT, RIGHT, UPPER and LOWER, and concatenation is usually written with the + or & symbol.
字符串使用内置操作而非算术来处理。常见伪代码函数包括 LENGTH、SUBSTRING、LEFT、RIGHT、UPPER、LOWER,连接通常用 + 或 & 表示。
If s = "Computer" then LENGTH(s) = 8, LEFT(s, 3) = "Com", RIGHT(s, 4) = "uter" and SUBSTRING(s, 3, 2) = "mp" ng that a postcode contains a space, or that a password is at least eight characters long.
若 s = "Computer",则 LENGTH(s) = 8,LEFT(s, 3) = "Com",RIGHT(s, 4) = "uter",SUBSTRING(s, 3, 2) = "mp"。这些函数可用于输入校验,例如检查邮编是否包含空格,或密码是否至少有八个字符。
Type casting converts a value from one data type to another. Implicit casting happens automatically, for example when an integer is used where a real is expected; explicit casting is written by the programmer, such as INT(3.9) which gives 3 by truncation, or STR(42) which produces the string "42".
类型转换把值从一种数据类型变为另一种。隐式转换自动发生,例如在需要实数的地方使用整数时;显式转换由程序员书写,例如 INT(3.9) 截断后得到 3,或 STR(42) 得到字符串 "42"。
A common exam trap is concatenating a number with a string. "Score: " + 42 fails in a strongly typed language because the types differ, so the integer must first be cast: "Score: " + STR(42).
考试中常见的陷阱是数字与字符串连接。"Score: " + 42 在强类型语言中会出错,因为类型不同,必须先转换: "Score: " + STR(42)。
5. Sequence and Selection | 顺序结构与选择结构
Control structures determine the order in which statements execute. The three fundamental structures are sequence, selection and iteration, and every algorithm can be expressed using only these three plus subroutines.
控制结构决定语句执行的顺序。三种基本结构是顺序、选择和迭代,任何算法都可以只用这三者加上子程序来表达。
Sequence is the default: statements run one after another, top to bottom. Selection allows a program to take different paths depending on a condition, using IF, ELSE IF and ELSE, terminated by ENDIF.
顺序是默认方式:语句自上而下依次执行。选择让程序根据条件走不同分支,使用 IF、ELSE IF 和 ELSE,并以 ENDIF 结束。
A simple pseudocode selection looks like this: IF mark ≥ 80 THEN grade ← "A" ELSE IF mark ≥ 70 THEN grade ← "A*" ... wait, keep it clean:
一个简单的选择伪代码如下:IF mark ≥ 80 THEN grade ← "A" ELSE IF mark ≥ 70 THEN grade ← "B" ELSE grade ← "C" ENDIF。条件按顺序测试,第一个为真的分支被执行,其余分支被跳过。
Conditions are evaluated in order, the first true branch runs, and all remaining branches are skipped. This is why the order of ELSE IF clauses matters: putting the broadest condition first would make the later, more specific tests unreachable.
条件按顺序求值,第一个为真的分支执行,其余分支全部跳过。这就是 ELSE IF 顺序很重要的原因:若把最宽泛的条件放在最前面,后面更具体的判断就永远无法到达。
A CASE statement is a cleaner alternative when one variable is compared against many fixed values, such as mapping a menu choice 1 to 4 to four different actions. CASE is easier to read, but IF is more flexible because it can combine several variables with AND and OR.
当一个变量需要与许多固定值比较时,CASE 语句是更清晰的选择,例如把菜单选项 1 至 4 映射为四种不同操作。CASE 更易读,而 IF 更灵活,因为它可以用 AND 和 OR 组合多个变量。
6. Iteration: Definite and Indefinite Loops | 迭代:计数循环与条件循环
Iteration repeats a block of statements. Definite (count-controlled) iteration repeats a known number of times, usually with FOR ... NEXT and a loop counter that is automatically incremented.
迭代用于重复执行一段语句。计数型(确定次数)迭代重复已知的次数,通常使用 FOR ... NEXT,循环计数器自动递增。
Indefinite (condition-controlled) iteration repeats until a condition changes. WHILE ... ENDWHILE tests the condition before each pass, so the body may never run; REPEAT ... UNTIL tests the condition after each pass, so the body always runs at least once.
条件型(不确定次数)迭代重复执行直到条件改变。WHILE ... ENDWHILE 在每轮之前测试条件,循环体可能一次都不执行;REPEAT ... UNTIL 在每轮之后测试条件,循环体至少执行一次。
The choice between the two is a frequent one-mark question. Use WHILE when zero repetitions are acceptable, and REPEAT when at least one pass is required, for example displaying a menu before asking the user to choose an option.
两者的选择是常见的一分题。若允许零次执行就用 WHILE;若至少需要执行一次就用 REPEAT,例如先显示菜单再让用户选择。
FOR i ← 1 TO 5 · WHILE count < 10 · REPEAT ... UNTIL count = 10
Two classic errors appear again and again. An off-by-one error uses the wrong boundary, such as FOR i ← 0 TO 5 when five items are needed. An infinite loop occurs when the condition can never become false, for example when the counter is never updated inside a WHILE loop.
两类经典错误反复出现。差一错误使用了错误的边界,例如需要处理五个数据却写成 FOR i ← 0 TO 5。死循环发生在条件永远无法变为假时,例如 WHILE 循环中计数器从未更新。
Loops can also be nested, with an inner loop completing all of its passes for each single pass of the outer loop. This is the standard technique for working with two-dimensional structures such as a grid, and the total number of passes is the product of the two ranges.
循环还可以嵌套,外层循环每执行一轮,内层循环就完整执行一遍。这是处理网格等二维结构的标准技巧,总执行次数为两个范围之积。
7. Dry Runs and Trace Tables | 人工推演与追踪表
A trace table (dry run) records the value of every variable after each step of an algorithm. It is the standard way to show that a program works, and it is directly assessed in exam questions.
追踪表(人工推演)记录算法每一步之后每个变量的取值。它是证明程序可用的标准方法,也是考试中直接考查的内容。
Consider a loop that adds the integers from 1 to 5 into a running total. The table has one column per variable plus a column for the output, and one row per iteration.
考虑一个把 1 到 5 的整数累加到总和的循环。表格中每个变量一列,再加一列输出,每轮迭代一行。
| i | total | Comment | 说明 |
|---|---|---|---|
| — | 0 | Initialisation | 初始化 |
| 1 | 1 | total ← 0 + 1 | 第一次累加 |
| 2 | 3 | total ← 1 + 2 | 第二次累加 |
| 3 | 6 | total ← 3 + 3 | 第三次累加 |
| 4 | 10 | total ← 6 + 4 | 第四次累加 |
| 5 | 15 | total ← 10 + 5 | 第五次累加,输出 15 |
The closed form of the same calculation is the arithmetic series formula, which confirms the trace is correct:
同一计算的闭式表达是等差数列求和公式,可用来验证追踪结果正确:
Σ from i = 1 to n of i = n(n + 1) ÷ 2, so for n = 5, total = 5 × 6 ÷ 2 = 15
When filling a trace table, only write a value in a column when the variable actually changes. Copying the previous value into every row wastes time and can hide the moment a variable is updated.
填写追踪表时,只有在变量真正改变时才在该列写值。把上一行的值照抄到每一行既浪费时间,也会掩盖变量更新发生的那一刻。
8. Subroutines: Procedures and Functions | 子程序:过程与函数
A subroutine is a named block of code that performs a specific task and can be called from elsewhere in the program. It hides complexity behind a meaningful name, so the main program reads like a list of steps.
子程序是一段有名字的代码块,用于完成特定任务,可被程序其他位置调用。它把复杂性隐藏在有意义的名称之后,使主程序读起来像一串步骤。
A procedure performs an action and does not return a value, such as PrintReceipt(). A function performs a calculation and returns exactly one value, such as CalculateVAT(price).
过程执行一个动作且不返回值,例如 PrintReceipt()。函数执行计算并恰好返回一个值,例如 CalculateVAT(price)。
The interface of a subroutine is its signature: the name plus the number, order and type of its parameters. As long as the interface stays the same, the body can be rewritten without breaking any calling code, which is what makes maintenance and team development practical.
子程序的接口即其签名:名称加上参数的数量、顺序与类型。只要接口不变,函数体可以重写而不影响任何调用代码,这正是可维护性与团队开发得以实现的原因。
- Avoids duplication, so a bug is fixed in one place only. | 避免重复,修改缺陷只需改一处。
- Makes programs easier to read and reason about. | 让程序更易读、更易推理。
- Allows each subroutine to be tested independently. | 允许对每个子程序独立测试。
- Supports teamwork on separate modules. | 支持团队分工开发不同模块。
9. Parameters and Scope | 参数传递与作用域
Parameter passing describes how data travels into and out of a subroutine. Passing by value copies the value, so changes inside the subroutine do not affect the caller's variable. Passing by reference passes the address, so changes are visible in the caller.
参数传递描述数据如何进出子程序。按值传递复制数值,因此子程序内的修改不影响调用方的变量。按引用传递传递地址,因此修改对调用方可见。
| Feature | 中文 | By value | By reference |
|---|---|---|---|
| What is copied | 复制内容 | The value | The address |
| Effect on caller | 对调用方影响 | None | Variable is updated |
| Typical use | 典型用途 | Read-only inputs | Returning multiple results |
Scope defines where a variable can be seen. A local variable exists only inside the subroutine that declares it, which prevents accidental interference. A global variable is visible throughout the program, which is convenient but makes debugging harder.
作用域定义变量的可见范围。局部变量只存在于声明它的子程序内部,可防止意外干扰。全局变量在整个程序中可见,使用方便但会增加调试难度。
Prefer local variables by default, and use globals only for genuine shared state such as a configuration constant or a game's score. A useful reason to remember: a function with only local variables is easier to test because its result depends solely on its parameters.
默认优先使用局部变量,仅在真正需要共享状态时使用全局变量,例如配置常量或游戏得分。一个值得记住的理由是:只使用局部变量的函数更易测试,因为其结果完全取决于参数。
10. Recursion | 递归
Recursion is a technique in which a subroutine calls itself. Every recursive solution needs a base case that stops the recursion, and a general (recursive) case that makes the problem smaller on each call.
递归是子程序调用自身的技术。每个递归解法都需要一个终止递归的基本情况(基例),以及一个在每次调用中让问题规模变小的递归情况(通例)。
The factorial function is the standard example. The base case is 0! = 1, and the general case reduces n by one on every call until the base case is reached.
阶乘函数是标准示例。基例是 0! = 1,通例在每次调用中把 n 减一,直到到达基例。
n! = 1 if n = 0; otherwise n! = n × (n − 1)!
base cases are F(0) = 0 and F(1) = 1, and the general case is F(n) = F(n − 1) + F(n − 2).
斐波那契数列遵循同样的模式,但会分成两个分支,因为每一项依赖前两项。基例是 F(0) = 0 与 F(1) = 1,通例是 F(n) = F(n − 1) + F(n − 2)。
Each call is placed on the call stack with its own copy of the parameters and local variables. The calls complete in reverse order, which is why recursion naturally unwinds, and why too many nested calls cause a stack overflow.
每次调用都会连同自己的参数与局部变量副本压入调用栈。调用按相反顺序返回,这正是递归能够自然回退的原因,也是嵌套调用过多会导致栈溢出的原因。
| Aspect | 中文 | style="border:1px solid #ccc;padding:
广告 / Sponsored 【正版新书】会计学 新时代新商科会计系列教材 洪荭 潘爱玲 东北财经大学出版社 9787565455209 商科、会计 备考教辅 · 正版现货 · 学习备考通用 查看详情 / View on Taobao参考价 ¥37.0广告 / Sponsored 现货英文原版计量经济分析施普林格商科与经济学教材Econometric Analysis of Panel Data … 商科、经济 备考教辅 · 正版现货 · 学习备考通用 查看详情 / View on Taobao参考价 ¥460.0更多咨询请联系16621398022(同微信) 备考资讯每日更新,关注不错过 考纲变化 · 科目分析 · 学习方法 ![]() 在微信里长按二维码识别关注 或截图后用「扫一扫 → 相册」选择本图 公众号:tutorhao |
|---|
