Tag: 编程

  • A-Level Programming Algorithms: Searching, Sorting and Complexity | A-Level 编程算法:查找、排序与复杂度

    📚 A-Level Programming Algorithms: Searching, Sorting and Complexity | A-Level 编程算法:查找、排序与复杂度

    Searching and sorting algorithms are the cornerstones of Edexcel A-Level programming. This topic connects abstract logical thinking with real program performance, and exam questions require you to trace code, compare Big O efficiency and justify algorithm choices.

    查找与排序算法是 Edexcel A-Level 编程的基石。这一主题将抽象逻辑思维与真实程序性能相结合,考试题目要求你跟踪代码、比较大 O 效率并证明算法选择的合理性。


    1. What Is an Algorithm? | 什么是算法?

    An algorithm is a finite sequence of well-defined steps that solves a specific problem. For Edexcel, you must be able to express algorithms in pseudocode, flowcharts and program code, and reason about their efficiency.

    算法是解决特定问题的有限且定义明确的步骤序列。对于 Edexcel,你必须能够用伪代码、流程图和程序代码表达算法,并对其效率进行推理。

    Key properties include clarity, termination, input and output. An algorithm must be precise enough for another programmer to implement it without ambiguity. For example, the instruction “sort the list” is not an algorithm because it does not state the exact comparison and swapping steps.

    关键性质包括清晰性、终止性、输入和输出。算法必须足够精确,使另一位程序员能够无歧义地实现它。例如,”对列表进行排序”这一指令不是算法,因为它没有说明确切的比较和交换步骤。

    • Input: values supplied to the algorithm | 输入:提供给算法的值
    • Output: at least one result produced | 输出:至少产生一个结果
    • Termination: stops after finite steps | 终止性:在有限步骤后停止
    • Definiteness: every step is clear and unambiguous | 明确性:每一步都清晰且无歧义

    2. Linear Search | 线性查找

    Linear search scans a list from index 0 to n-1, comparing each element with the target. It works on any list, whether sorted or unsorted, so it is useful when you have no guarantee about ordering.

    线性查找从索引 0 到 n-1 扫描列表,将每个元素与目标值进行比较。它对任何列表都有效,无论是有序还是无序,因此当你无法保证顺序时非常有用。

    Suppose we search for 42 in the list [15, 9, 42, 6, 30]. Linear search compares 15, then 9, then finds 42 at index 2 after 3 comparisons. If the target were 99, it would examine all 5 elements and return not found.

    假设我们在列表 [15, 9, 42, 6, 30] 中查找 42。线性查找依次比较 15、9,然后在索引 2 处找到 42,共比较 3 次。如果目标值是 99,它将检查全部 5 个元素并返回未找到。

    Its worst-case time complexity is O(n) because every element may need checking. For a list of 1,000 items, a full scan averages 500 comparisons and may need 1,000 when the target is absent or is the final element.

    其最坏时间复杂度是 O(n),因为可能需要检查每个元素。对于包含 1,000 个元素的列表,完整扫描平均需要 500 次比较,当目标不存在或是最后一个元素时最多可能需要 1,000 次。

    • Best case: O(1) when target is first | 最佳情况:目标在首位时为 O(1)
    • Worst case: O(n) when target is last or absent | 最坏情况:目标在末位或不存在时为 O(n)
    • Average case: O(n) for random input | 平均情况:随机输入为 O(n)

    3. Binary Search | 二分查找

    Binary search operates only on a sorted list. It finds the middle element, compares it

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Computer Science: Object-Oriented Programming (OOP) | Edexcel A-Level 计算机科学:面向对象编程(OOP)

    📚 Edexcel A-Level Computer Science: Object-Oriented Programming (OOP) | Edexcel A-Level 计算机科学:面向对象编程(OOP)

    Object-oriented programming (OOP) is a central paradigm in the Edexcel A-Level Computer Science specification. It models real-world entities using classes and objects, making complex programs easier to design, maintain, and extend. This article covers the key OOP concepts required for the exam: classes, objects, attributes, methods, constructors, encapsulation, inheritance, polymorphism, abstract classes, interfaces, static members, and aggregation. Each section presents the core idea in English followed by the equivalent Chinese explanation, with clear examples and exam tips.

    面向对象编程(OOP)是 Edexcel A-Level 计算机科学大纲中的核心范式。它使用类和对象来模拟现实世界实体,使复杂程序更易于设计、维护和扩展。本文涵盖考试所需的关键 OOP 概念:类、对象、属性、方法、构造函数、封装、继承、多态、抽象类、接口、静态成员和聚合。每一节先用英文呈现核心思想,再用对应的中文解释,并配有清晰的示例和考试提示。


    1. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes (data) and methods (behaviour) common to all objects of a certain kind. An object is a specific instance of a class, created at runtime with its own identity and state. For example, the class Student may define attributes such as name and grade, while an object of this class could be student1 with the values "Alice" and "A".

    类是定义某一类对象共有的属性(数据)和方法(行为)的蓝图或模板。对象是类的具体实例,在运行时创建,具有自己的标识和状态。例如,类 Student 可以定义 namegrade 等属性,而该类的一个对象可以是 student1,其值为 "Alice""A"

    In most languages, class names start with a capital letter, and object creation uses the new keyword or a constructor call. You can create many objects from one class, each storing different data while sharing the same structure and methods.

    在大多数语言中,类名以大写字母开头,创建对象使用 new 关键字或构造函数调用。你可以从一个类创建多个对象,每个对象存储不同的数据,但共享相同的结构和方法。


    2. Attributes and Methods | 属性与方法

    Attributes, also called fields or properties, are variables that belong to an object and store its state. Methods are functions defined inside a class that describe the behaviours an object can perform. In a BankAccount class, the attribute balance stores the current amount, and the method deposit() increases that balance.

    属性,也称为字段或特性,是属于对象的变量,用于存储对象的状态。方法是在类内部定义的函数,描述对象可以执行的行为。在 BankAccount 类中,属性 balance 存储当前金额,方法 deposit() 增加该余额。

    When you call an object’s method, it can access and modify that object’s attributes. This is different from a standalone function, which has no persistent state tied to an object.

    当你调用对象的方法时,它可以访问和修改该对象的属性。这与独立函数不同,独立函数没有绑定到对象的持久状态。


    3. Constructors and Instantiation | 构造函数与实例化

    A constructor is a special method that runs automatically when an object is created. It usually initialises the object’s attributes with starting values. In Python, the constructor is named __init__; in Java and C#, it has the same name as the class. A constructor may accept parameters to set different initial states for different objects.

    构造函数是一种特殊方法,在对象创建时自动运行。它通常用初始值来初始化对象的属性。在 Python 中,构造函数名为 __init__;在 Java 和 C# 中,它与类同名。构造函数可以接受参数,为不同对象设置不同的初始状态。

    Instantiation is the process of creating an object from a class. For example, new Student("Alice", "A") calls the constructor and returns a new object with those attribute values. Without a constructor, attributes may remain uninitialised or default to zero or null.

    实例化是从类创建对象的过程。例如,new Student("Alice", "A") 调用构造函数并返回一个带有这些属性值的新对象。如果没有构造函数,属性可能保持未初始化或默认为零或空值。


    4. Encapsulation and Access Modifiers | 封装与访问修饰符

    Encapsulation means hiding the internal state of an object and exposing only a controlled interface. This protects data from accidental corruption and makes the code easier to debug. Access modifiers such as public, private, and protected control whether attributes or methods can be accessed from outside the class.

    封装意味着隐藏对象的内部状态,只暴露受控的接口。这可以保护数据免受意外破坏,并使代码更易于调试。访问修饰符如 publicprivateprotected 控制属性或方法是否可以从类外部访问。

    Typically, attributes are declared private, and public methods called getters and setters are provided to read or modify them. For example, a getBalance() method allows read-only access, while a setBalance() method may include validation rules.

    通常,属性被声明为 private,并提供称为 getter 和 setter 的公共方法来读取或修改它们。例如,getBalance() 方法允许只读访问,而 setBalance() 方法可以包含验证规则。


    5. Inheritance | 继承

    Inheritance allows a new class (child or subclass) to inherit attributes and methods from an existing class (parent or superclass). This promotes code reuse and establishes a natural hierarchy. The child class can add new attributes and methods or modify inherited ones.

    继承允许新类(子类)从现有类(父类或超类)继承属性和方法。这促进了代码复用,并建立了自然的层次结构。子类可以添加新的属性和方法,或修改继承的方法。

    For example, a Vehicle class may have attributes speed and method move(). A Car class can inherit these and add a numberOfDoors attribute. In code, Java uses the extends keyword, Python uses parentheses: class Car(Vehicle).

    例如,Vehicle 类可以具有属性 speed 和方法 move()Car 类可以继承这些,并添加 numberOfDoors 属性。在代码中,Java 使用 extends 关键字,Python 使用括号:class Car(Vehicle)


    6. Polymorphism and Method Overriding | 多态与方法重写

    Polymorphism means “many forms”. In OOP, it allows objects of different classes to respond to the same method call in their own way. Method overriding is a key technique: a child class provides a different implementation of a method that already exists in the parent class.

    多态意味着“多种形式”。在面向对象编程中,它允许不同类的对象以自己的方式响应同一个方法调用。方法重写是一项关键技术:子类为父类中已存在的方法提供不同的实现。

    Suppose both Cat and Dog classes inherit from Animal and override the speak() method. A single loop over a list of Animal objects can call speak(), and each object produces the correct sound. This simplifies code that works with groups of related objects.

    假设 CatDog 类都继承自 Animal,并重写了 speak() 方法。一个对 Animal 对象列表的循环可以调用 speak(),每个对象都会产生正确的声音。这简化了处理相关对象组的代码。


    7. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class cannot be instantiated directly; it only provides a base for subclasses. It may contain abstract methods (methods without a body) that subclasses must implement. This enforces a common structure while leaving specific behaviour to child classes.

    抽象类不能被直接实例化;它只为子类提供基类。它可以包含抽象方法(没有方法体的方法),子类必须实现这些方法。这强制了公共结构,同时将具体行为留给子类。

    An interface is similar but defines only method signatures, with no implementation at all. A class can implement multiple interfaces, but inherit from only one abstract class. In exam questions, you may be asked to identify when an abstract class or interface is more appropriate.

    接口类似,但只定义方法签名,完全没有实现。一个类可以实现多个接口,但只能继承一个抽象类。在考试题中,可能会要求你判断何时使用抽象类或接口更合适。


    8. Static Members and Class Variables | 静态成员与类变量

    Static members belong to the class itself rather than to any individual object. A static variable is shared across all instances of the class, while a static method can be called without creating an object. They are useful for constants, counters, or utility functions that do not depend on object state.

    静态成员属于类本身,而不是属于任何单个对象。静态变量在类的所有实例之间共享,而静态方法无需创建对象即可调用。它们适用于常量、计数器或不依赖对象状态的工具函数。

    For example, a Student class might have a static variable count that increments in the constructor to track how many students have been created. In Java, the static keyword is used; in Python, class variables are defined directly within the class body.

    例如,Student 类可以有一个静态变量 count,在构造函数中递增以跟踪已创建的学生数量。在 Java 中,使用 static 关键字;在 Python 中,类变量直接定义在类体内。


    9. Aggregation and Composition | 聚合与组合

    Aggregation and composition describe relationships where one class contains a reference to another class as an attribute. Both model “has-a” relationships, but they differ in the strength of ownership. In composition, the contained object cannot exist independently of the container; in aggregation, it can.

    聚合和组合描述一个类包含另一个类的引用作为属性的关系。两者都建模“有一个”关系,但在所有权的强度上有所不同。在组合中,被包含的对象不能独立于容器存在;在聚合中,它可以独立存在。

    For example, a University has Department objects (aggregation: departments can exist without the university), but a House has Room objects (composition: rooms are destroyed if the house is destroyed). Exam questions may test your ability to distinguish between these relationships.

    例如,UniversityDepartment 对象(聚合:系可以在没有大学的情况下存在),但 HouseRoom 对象(组合:如果房子被摧毁,房间也会被摧毁)。考试题可能会测试你区分这些关系的能力。


    10. Design Principles and Exam Tips | 设计原则与考试技巧

    Strong OOP design follows principles such as DRY (Don’t Repeat Yourself) and encapsulation. You should aim to keep classes focused on a single responsibility, use inheritance only when a genuine “is-a” relationship exists, and prefer interfaces over implementation inheritance when flexibility is needed.

    良好的面向对象设计遵循 DRY(不要重复自己)和封装等原则。你应该力求让类专注于单一职责,仅在存在真正的“是一个”关系时使用继承,并在需要灵活性时优先使用接口而不是实现继承。

    In the Edexcel exam, you may be given pseudocode or a short program and asked to identify OOP concepts, correct errors, or write a small class definition. Practise drawing simple class diagrams and converting between pseudocode and real code. Remember to use access modifiers appropriately and explain why encapsulation improves maintainability.

    在 Edexcel 考试中,可能会给你伪代码或简短程序,要求你识别面向对象概念、纠正错误或编写一个小的类定义。练习绘制简单的类图,并在伪代码和真实代码之间转换。记住适当使用访问修饰符,并解释封装为何能提高可维护性。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Programming Fundamentals and Computational Thinking | 编程基础与计算思维

    📚 Programming Fundamentals and Computational Thinking | 编程基础与计算思维

    This revision guide covers the core programming and computational thinking skills required for Edexcel A-Level Computer Science. It is designed to help you understand how programs are designed, written, tested and evaluated, and to prepare for both Paper 1 and Paper 2 programming questions.

    本复习指南涵盖 Edexcel A-Level 计算机科学所需的核心编程与计算思维技能。它旨在帮助你理解程序如何被设计、编写、测试和评估,并为 Paper 1 和 Paper 2 的编程题做好准备。


    1. Computational Thinking | 计算思维

    Computational thinking involves breaking down complex problems into smaller, more manageable parts. The three key techniques are decomposition, pattern recognition and abstraction. Decomposition means splitting a problem into sub-problems. Pattern recognition identifies similarities with previously solved problems. Abstraction focuses on relevant information while ignoring unnecessary detail.

    计算思维涉及将复杂问题分解为更小、更易于处理的部分。三种关键技术是分解、模式识别和抽象。分解意味着把一个问题拆分成若干子问题。模式识别识别与已解决问题之间的相似性。抽象则聚焦于相关信息,忽略不必要的细节。

    Algorithmic thinking is the process of defining a clear, step-by-step solution to a problem. A good algorithm is precise, finite and unambiguous. These skills are explicitly assessed in Edexcel programming questions, where you must design a solution before writing code.

    算法思维是定义一个清晰、逐步解决问题的过程。好的算法是精确、有限且无歧义的。这些技能在 Edexcel 编程题中会被直接考查,你必须在编写代码之前先设计解决方案。

    • Decomposition – breaking a problem into smaller parts (分解 – 将问题拆分为更小的部分)
    • Pattern recognition – spotting similarities with known problems (模式识别 – 发现与已知问题的相似性)
    • Abstraction – ignoring unnecessary detail to focus on key features (抽象 – 忽略不必要细节,聚焦关键特征)

    2. Programming Paradigms | 编程范式

    Edexcel expects awareness of different programming paradigms, mainly procedural, object-oriented and event-driven. Procedural programming uses step-by-step instructions and functions to manipulate data. Object-oriented programming organises code into classes and objects with attributes and methods. Event-driven programming responds to user actions such as button clicks.

    Edexcel 要求了解不同的编程范式,主要是过程式、面向对象和事件驱动。过程式编程使用逐步指令和函数来操作数据。面向对象编程将代码组织成具有属性和方法的类和对象。事件驱动编程则响应用户操作,例如按钮点击。

    Paradigm Key Idea Typical Use
    Procedural Series of instructions; functions/procedures Scientific calculations, simple utilities
    Object-oriented Classes, objects, encapsulation, inheritance Large applications, GUI systems
    Event-driven Code executes in response to events Interactive interfaces, mobile apps

    You should be able to compare these paradigms and justify why one may be more suitable for a given problem. For example, an object-oriented approach is often chosen when the system models real-world entities with shared behaviour.

    你应该能够比较这些范式,并说明为什么某个范式更适合给定的问题。例如,当系统对具有共同行为的现实世界实体进行建模时,通常会选择面向对象方法。


    3. Variables, Constants and Data Types | 变量、常量与数据类型

    Programs store data in named memory locations called variables. A constant is a value that cannot be changed during execution. Common data types include integer, real (float), Boolean, character, string and date/time. Choosing the correct data type is important for memory efficiency and for validation.

    程序在称为变量的命名内存位置中存储数据。常量是在执行期间不能更改的值。常见的数据类型包括整数、实数(浮点)、布尔、字符、字符串和日期/时间。选择正确的数据类型对于内存效率和验证非常重要。

    Data Type Description Example
    Integer Whole number 42
    Real / Float Decimal number 3.14
    Boolean True or False only True
    Character Single symbol ‘A’
    String Sequence of characters “Hello”

    Implicit and explicit type conversion can cause errors if not handled carefully. In many languages, adding an integer to a floating-point number promotes the integer to a float automatically, but converting a string to an integer requires explicit casting or parsing.

    隐式和显式类型转换如果不小心处理可能会导致错误。在许多语言中,整数与浮点数相加会自动将整数提升为浮点数,但将字符串转换为整数则需要显式转换或解析。


    4. Control Structures: Sequence, Selection, Iteration | 控制结构:顺序、选择、迭代

    All programs are built from three control structures: sequence, selection and iteration. Selection uses IF, ELSE IF and ELSE statements to make decisions. Iteration repeats code using FOR, WHILE or REPEAT UNTIL loops. Sequence is the default order of execution.

    所有程序都由三种控制结构构建:顺序、选择和迭代。选择使用 IF、ELSE IF 和 ELSE 语句来做出决策。迭代使用 FOR、WHILE 或 REPEAT UNTIL 循环来重复代码。顺序是默认的执行顺序。

    Below is a typical selection statement written in pseudocode. It assigns a grade based on a numeric score. Note the use of ≥ for ‘greater than or equal to’.

    下面是一个用伪代码编写的典型选择语句。它根据数值分数分配等级。注意使用 ≥ 表示“大于或等于”。

    IF score ≥ 75 THEN
      grade = ‘A’
    ELSE IF score ≥ 60 THEN
      grade = ‘B’
    ELSE
      grade = ‘C’
    END IF

    Iteration can be count-controlled or condition-controlled. A FOR loop executes a fixed number of times, while a WHILE loop continues as long as a condition is true. A REPEAT UNTIL loop always executes at least once before checking the condition.

    迭代可以是计数控制或条件控制。FOR 循环执行固定次数,而 WHILE 循环在条件为真时继续执行。REPEAT UNTIL 循环在检查条件之前至少执行一次。


    5. Functions and Procedures | 函数与过程

    A function is a named block of code that returns a value, while a procedure performs a task but returns no value. Parameters allow data to be passed into functions and procedures. Using functions improves modularity, reusability and readability of code.

    函数是一个返回值的命名代码块,而过程执行任务但不返回值。参数允许将数据传递给函数和过程。使用函数可以提高代码的模块化、可重用性和可读性。

    Parameters can be passed by value or by reference. In pass by value, a copy of the argument is made, so the original variable is not changed. In pass by reference, the function can modify the original variable’s value. Edexcel questions often ask you to trace the effect of parameter passing.

    参数可以按值或按引用传递。在按值传递中,会创建实参的副本,因此原始变量不会被改变。在按引用传递中,函数可以修改原始变量的值。Edexcel 题目常要求你跟踪参数传递的效果。

    • Functions return a value; procedures do not (函数返回值;过程不返回值)
    • Parameters improve code reuse (参数提高代码重用性)
    • Modular code is easier to test and debug (模块化代码更易于测试和调试)

    6. Data Structures: Arrays, Lists, Records | 数据结构:数组、列表、记录

    Arrays store multiple elements of the same data type in contiguous memory locations. A 1D array is like a list, while a 2D array represents a table or matrix. Indexing usually starts at 0, so the first element is array[0].

    数组在连续的内存位置中存储多个相同数据类型的元素。一维数组类似列表,而二维数组代表表格或矩阵。索引通常从 0 开始,因此第一个元素是 array[0]。

    Records group related fields of different data types into one structure. For example, a student record might contain a string name, an integer age and a real average mark. Lists in languages like Python are dynamic and can hold mixed types, but this flexibility comes with memory overhead.

    记录将不同数据类型的相关字段组合成一个结构。例如,学生记录可能包含字符串姓名、整数年龄和实数平均分。像 Python 这样的语言中的列表是动态的,可以容纳混合类型,但这种灵活性会带来内存开销。

    Understanding the distinction between a static array, which has a fixed size, and a dynamic list, which can grow or shrink, is essential for answering Edexcel data structure questions.

    理解静态数组(大小固定)与动态列表(可以扩展或收缩)之间的区别,对于回答 Edexcel 数据结构问题至关重要。


    7. File Handling and Exceptions | 文件处理与异常

    File handling allows programs to read from and write to external files such as text or CSV files. Common operations include open, read, write, append and close. Opening a file usually requires specifying a mode: read (‘r’), write (‘w’), append (‘a’) or read/write (‘r+’).

    文件处理允许程序读取和写入外部文件,例如文本文件或 CSV 文件。常见操作包括打开、读取、写入、追加和关闭。打开文件通常需要指定模式:读取 (‘r’)、写入 (‘w’)、追加 (‘a’) 或读写 (‘r+’)。

    Exception handling uses TRY-EXCEPT blocks to manage runtime errors like missing files or invalid input without crashing the program. When an error occurs inside the TRY block, control jumps to the EXCEPT block where a recovery action can be taken. This improves robustness.

    异常处理使用 TRY-EXCEPT 块来管理运行时错误,例如文件缺失或输入无效,而不会使程序崩溃。当 TRY 块内发生错误时,控制权会跳转到 EXCEPT 块,在那里可以采取恢复措施。这提高了程序的健壮性。

    • Open a file before reading or writing (在读写之前打开文件)
    • Close files after use to free resources (使用后关闭文件以释放资源)
    • Use TRY-EXCEPT to handle file not found errors (使用 TRY-EXCEPT 处理文件未找到错误)

    8. Algorithms: Searching and Sorting | 算法:搜索与排序

    Searching algorithms include linear search and binary search. Linear search checks every element sequentially with average time complexity O(n). Binary search requires a sorted list and halves the search space each time, giving O(log n).

    搜索算法包括线性搜索和二分搜索。线性搜索顺序检查每个元素,平均时间复杂度为 O(n)。二分搜索要求列表有序,每次将搜索空间减半,时间复杂度为 O(log n)。

    Linear search: O(n)   |   Binary search: O(log n)

    Sorting algorithms include bubble sort, insertion sort and merge sort. Bubble sort repeatedly compares adjacent elements and swaps them if they are out of order. Insertion sort builds the sorted list one element at a time. Merge sort divides the list into halves, sorts each half recursively, then merges them.

    排序算法包括冒泡排序、插入

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Programming Fundamentals: Data Types, Variables and Control Structures | 编程基础:数据类型、变量与控制结构

    📚 Programming Fundamentals: Data Types, Variables and Control Structures | 编程基础:数据类型、变量与控制结构

    In Edexcel A-Level Computer Science, the programming paper tests your ability to design, write and trace algorithms using a clear pseudocode style. This article covers the core programming building blocks: data types, variables, constants, operators, selection, iteration, arrays, strings and subprograms.

    在 Edexcel A-Level 计算机科学考试中,编程部分考查你使用清晰的伪代码风格设计、编写和跟踪算法的能力。本文涵盖核心编程构建模块:数据类型、变量、常量、运算符、选择结构、迭代、数组、字符串和子程序。


    1. Programming and Pseudocode | 编程与伪代码

    Programming is the process of creating a set of instructions that a computer can execute to solve a problem. In Edexcel exams, you are expected to express algorithms in a standard pseudocode syntax rather than a specific programming language.

    编程是创建一组计算机能够执行以解决问题的指令的过程。在 Edexcel 考试中,你需要使用标准伪代码语法来表达算法,而不是某种特定编程语言。

    Pseudocode should be clear, unambiguous and consistent. Common Edexcel conventions include INPUT for input, OUTPUT for output, for assignment, and keywords such as IF, WHILE, FOR and ENDIF.

    伪代码应清晰、无歧义且一致。常见的 Edexcel 规范包括:用 INPUT 表示输入,OUTPUT 表示输出, 表示赋值,以及 IFWHILEFORENDIF 等关键字。

    OUTPUT “Enter age”

    This simple statement displays a message. You can include it as part of an algorithm.

    这个简单语句用于显示一条消息。你可以将其作为算法的一部分。


    2. Variables, Constants and Assignment | 变量、常量与赋值

    A variable is a named storage location whose value can change while a program is running. A constant is a named value that cannot be changed after it is assigned.

    变量是一个命名的存储位置,其值在程序运行期间可以改变。常量是一个命名的值,在赋值之后不能改变。

    Assignment stores a value in a variable. In Edexcel pseudocode, the left arrow is used: score ← 0. This means ‘set the variable score to 0’.

    赋值将值存储到变量中。在 Edexcel 伪代码中,使用左箭头 score ← 0。这表示“将变量 score 设置为 0”。

    Constants are often written in upper case, for example MAX_ITEMS ← 100. They improve readability and prevent accidental changes.

    常量通常使用大写字母书写,例如 MAX_ITEMS ← 100。它们可以提高可读性并防止意外修改。


    3. Primitive Data Types | 原始数据类型

    Edexcel pseudocode recognises several primitive data types. Choosing the correct type affects how data is stored and what operations are valid.

    Edexcel 伪代码识别几种原始数据类型。选择正确的类型会影响数据的存储方式以及合法的操作。

    Data type Meaning Example
    Integer Whole number, positive or negative -3, 0, 42
    Real/Float Number with a fractional part 3.14, -0.5
    Boolean True or False only TRUE, FALSE
    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming in Edexcel A-Level Computer Science | Edexcel A-Level 计算机科学中的面向对象编程

    📚 Object-Oriented Programming in Edexcel A-Level Computer Science | Edexcel A-Level 计算机科学中的面向对象编程

    Object-oriented programming (OOP) is a fundamental paradigm in Edexcel A-Level Computer Science. It allows programs to be modelled around real-world entities, making code more modular, reusable and easier to maintain. In the exam, you need to understand classes, objects, encapsulation, inheritance, polymorphism, constructors and instantiation, as well as be able to interpret and write simple OOP code.

    面向对象编程 (OOP) 是 Edexcel A-Level 计算机科学中的核心范式。它让程序围绕现实世界中的实体建模,使代码更加模块化、可复用且易于维护。在考试中,你需要掌握类、对象、封装、继承、多态、构造函数和实例化,并能阅读和编写简单的 OOP 代码。


    1. What is Object-Oriented Programming? | 什么是面向对象编程?

    Object-oriented programming is a programming paradigm that organises software design around data, or objects, rather than functions and logic. An object is a self-contained entity that contains both data and the methods that operate on that data. This contrasts with procedural programming, where data and procedures are separate. OOP models real-world entities such as students, bank accounts or cars, making it easier to conceptualise and maintain complex systems.

    面向对象编程是一种围绕数据(对象)而非函数和逻辑来组织软件设计的编程范式。对象是自包含的实体,既包含数据,也包含操作这些数据的方法。这与过程式编程不同,在过程式编程中数据和过程是分离的。OOP 对学生、银行账户或汽车等现实世界实体进行建模,使复杂系统更容易理解和维护。

    In Edexcel exams, you may be asked to compare OOP with other paradigms such as procedural programming. Key points to remember are that OOP bundles data and behaviour together and supports reuse through inheritance. The real-world modelling aspect is often assessed in short-answer questions.

    在 Edexcel 考试中,你可能会被要求将 OOP 与过程式编程等其它范式进行比较。需要记住的关键点是 OOP 将数据和行为捆绑在一起,并通过继承支持复用。现实世界建模这一特点经常在简答题中考查。


    2. Classes and Objects | 类与对象

    A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (behaviour) that objects of that class will have. For example, a class Car might define attributes such as colour, make and currentSpeed, and methods such as accelerate() and brake(). An object is a specific instance of a class. If Car is the blueprint, then myCar = Car(“red”, “Toyota”, 0) creates a concrete object with those values.

    类是创建对象的蓝图或模板。它定义了该类的对象将具有的属性(数据)和方法(行为)。例如,Car 类可以定义颜色、品牌和当前速度等属性,以及 accelerate() 和 brake() 等方法。对象是类的具体实例。如果说 Car 是蓝图,那么 myCar = Car(“red”, “Toyota”, 0) 就创建了一个具有这些值的具体对象。

    It is important not to confuse a class with an object. A class exists at design time as a piece of code, while an object exists at run time and occupies memory. In a class diagram, the class name is usually shown in the top compartment, attributes in the middle, and methods at the bottom.

    重要的是不要将类与对象混淆。类在设计时作为一段代码存在,而对象在运行时存在并占用内存。在类图中,类名通常显示在顶部框中,属性在中间,方法在底部。


    3. Attributes and Methods | 属性与方法

    Attributes are the data stored inside an object. They represent the state of the object and are often called fields or properties. Methods are functions defined inside a class that describe the behaviours an object can perform. In Edexcel exams, you may be asked to identify attributes and methods from a class diagram or a code snippet. Remember: attributes are nouns, methods are verbs. For example, in a Student class, name, age and grade are attributes, while enrol(), sitExam() and getGrade() are methods.

    属性是存储在对象内部的数据。它们表示对象的状态,通常也被称为字段或属性。方法是在类内部定义的函数,描述对象能够执行的行为。在 Edexcel 考试中,你可能需要从类图或代码片段中识别属性和方法。记住:属性是名词,方法是动词。例如,在 Student 类中,name、age 和 grade 是属性,而 enrol()、sitExam() 和 getGrade() 是方法。

    Methods often use the object’s attributes to produce results or change state. For instance, an accelerate() method might increase the currentSpeed attribute by a fixed amount. Some methods return a value, while others simply perform an action and return nothing.

    方法通常使用对象的属性来产生结果或改变状态。例如,accelerate() 方法可能会将 currentSpeed 属性增加一个固定值。有些方法返回值,而另一些方法仅执行操作并不返回任何内容。


    4. Constructors and Instantiation | 构造函数与实例化

    A constructor is a special method that is called automatically when an object is created. It usually initialises the object’s attributes. In Python, the constructor is __init__; in Java, it has the same name as the class. Instantiation is the process of creating an object from a class using the constructor. For example, Student s1 = new Student(“Alice”, 17); in Java instantiates a Student object and calls the constructor to set initial values. The keyword new is used in Java, while Python simply calls the class name: s1 = Student(“Alice”, 17).

    构造函数是一种特殊的方法,在创建对象时会自动调用。它通常用于初始化对象的属性。在 Python 中,构造函数是 __init__;在 Java 中,它与类同名。实例化是使用构造函数从类创建对象的过程。例如,Student s1 = new Student(“Alice”, 17); 在 Java 中实例化一个 Student 对象并调用构造函数设置初始值。Java 中使用关键字 new,而 Python 直接调用类名:s1 = Student(“Alice”, 17)。

    A constructor may have parameters to pass initial values, or it may be a default constructor with no parameters. If no constructor is written, some languages provide a default one that sets attributes to null or zero. In Edexcel pseudocode, the constructor is often written as a procedure called new or init.

    构造函数可以带有参数以传递初始值,也可以是无参数的默认构造函数。如果没有编写构造函数,某些语言会提供一个默认构造函数,将属性设置为 null 或零。在 Edexcel 伪代码中,构造函数通常写成一个名为 new 或 init 的过程。


    5. Encapsulation and Access Modifiers | 封装与访问修饰符

    Encapsulation is the technique of hiding an object’s internal state and requiring all interaction to happen through methods. This protects data from being changed in unexpected ways. Access modifiers control the visibility of attributes and methods. Common modifiers are public (accessible from anywhere), private (only accessible inside the class) and protected (accessible inside the class and its subclasses). In Python, the convention is to use a single underscore _ for protected and double underscore __ for private, though it is not strictly enforced. Encapsulation helps build robust code by enforcing a controlled interface.

    封装是一种隐藏对象内部状态并要求所有交互都必须通过方法进行的技术。这可以保护数据不被意外修改。访问修饰符控制属性和方法的可见性。常见的修饰符包括 public(任何地方均可访问)、private(只能在类内部访问)和 protected(类及其子类内部可访问)。在 Python 中,约定使用单下划线 _ 表示受保护,双下划线 __ 表示私有,但这并不是严格强制执行的。封装通过强制受控接口来构建健壮的代码。

    Access modifier Python convention Visibility
    public no underscore everywhere
    protected _attribute class and subclasses
    private __attribute class only

    In practice, private attributes are accessed through public getter and setter methods, such as getName() and setName(). This allows validation and maintains control over how data is modified.

    在实际中,私有属性通过公共的 getter 和 setter 方法访问,例如 getName() 和 setName()。这样可以在修改数据时进行验证并保持控制。


    6. Inheritance | 继承

    Inheritance allows a new class (subclass) to acquire the attributes and methods of an existing class (superclass). The subclass can add new attributes and methods or override inherited ones. This promotes code reuse and models ‘is-a’ relationships. For example, a class Dog can inherit from a class Animal, so Dog gets attributes such as name and age and methods such as eat() and sleep(), and can add a bark() method. In Java, inheritance uses the keyword extends; in Python, the parent class is placed in parentheses: class Dog(Animal).

    继承允许新类(子类)获取现有类(父类)的属性和方法。子类可以添加新的属性和方法,或者重写继承的方法。这促进了代码复用并建模“是”关系。例如,Dog 类可以继承 Animal 类,因此 Dog 获得 name 和 age 等属性以及 eat() 和 sleep() 等方法,还可以添加 bark() 方法。在 Java 中,继承使用关键字 extends;在 Python 中,父类放在括号内:class Dog(Animal)。

    Inheritance creates a class hierarchy. At the top is the most general superclass, and as we move down, classes become more specific. Multiple levels of inheritance are possible, but a subclass usually has only one direct parent in languages like Java to avoid complexity. The super keyword is used to call the superclass constructor or methods.

    继承创建了类层次结构。顶部是最通用的父类,向下移动时,类变得越来越具体。多级继承是可能的,但在 Java 等语言中,子类通常只有一个直接父类,以避免复杂性。super 关键字用于调用父类的构造函数或方法。


    7. Overriding and Polymorphism | 重写与多态

    Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. Polymorphism means ‘many forms’ and allows a single interface to represent different underlying types. For example, a superclass Shape may have a method area(), and subclasses Circle and Rectangle override area() with their own formulae. A polymorphic call such as shape.area() will invoke the correct version depending on the actual object type at run time. Polymorphism is often tested in Edexcel exams via code tracing questions.

    方法重写发生在子类为其父类中已经定义的方法提供不同实现时。多态意为“多种形态”,它允许单个接口表示不同的底层类型。例如,父类 Shape 可以有一个 area() 方法,子类 Circle 和 Rectangle 用自己的公式重写 area()。多态调用如 shape.area() 将根据运行时实际对象类型调用正确的版本。Edexcel 考试经常通过代码跟踪题来测试多态。

    Dynamic dispatch is the mechanism behind polymorphism. When a method is called on a reference variable, the actual method executed depends on the object’s type, not the reference type. This allows writing flexible code that can work with any subclass without knowing its exact type at compile time.

    动态分派是多态背后的机制。当在引用变量上调用方法时,实际执行的方法取决于对象的类型,而不是引用类型。这允许编写灵活的代码,可以在不知道编译时确切类型的情况下处理任何子类。


    8. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class is a class that cannot be instantiated directly and may contain abstract methods—methods without a body that must be implemented by subclasses. An interface is a contract that specifies a set of methods that a class must implement, without providing any implementation. In Java, abstract classes use the keyword abstract, and interfaces use interface. Python supports abstract base classes via the abc module. These constructs support design flexibility and guarantee that certain methods exist.

    抽象类是不能直接实例化的类,它可以包含抽象方法——即没有方法体、必须由子类实现的方法。接口是一种契约,规定类必须实现的一组方法,但不提供任何实现。在 Java 中,抽象类使用关键字 abstract,接口使用 interface。Python 通过 abc 模块支持抽象基类。这些结构支持设计灵活性,并保证某些方法一定存在。

    Abstract classes can have both concrete and abstract methods, while interfaces traditionally only declare method signatures. A class can implement multiple interfaces but typically extend only one abstract class. This distinction is useful in design questions where you need to choose the right construct for a given scenario.

    抽象类可以同时具有具体方法和抽象方法,而接口传统上只声明方法签名。一个类可以实现多个接口,但通常只能继承一个抽象类。这种区别在设计题中很有用,在这些题中你需要为给定场景选择合适的结构。

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operators and Expressions in Edexcel A Level Programming | Edexcel A Level 编程中的运算符与表达式

    📚 Operators and Expressions in Edexcel A Level Programming | Edexcel A Level 编程中的运算符与表达式

    Expressions are the building blocks of every program. In Edexcel A Level Computer Science, you need to combine literals, variables, operators, and function calls to produce values, control flow, and Boolean logic. This article explains the operators you must know, their precedence, and how to evaluate them accurately in exam questions.

    表达式是每个程序的基本构造块。在 Edexcel A Level 计算机科学中,你需要组合字面量、变量、运算符和函数调用,以产生值、控制流程和布尔逻辑。本文解释你必须掌握的运算符、它们的优先级,以及如何在考试题中准确求值。


    1. Data Types and Literals | 数据类型与字面量

    In programming, a literal is a fixed value written directly in the code. The value’s type determines which operations are allowed. Edexcel pseudocode expects you to distinguish clearly between integer, real (float), Boolean, character, and string data types.

    在编程中,字面量是直接写在代码中的固定值。值的类型决定了允许哪些运算。Edexcel 伪代码要求你明确区分整数、实数(浮点数)、布尔值、字符和字符串数据类型。

    Examples of literals: 42 (integer), 3.14 (real), True (Boolean), 'A' (character), and "hello" (string). Mixing incompatible types without casting can cause errors or unexpected results.

    字面量示例:42(整数)、3.14(实数)、True(布尔值)、'A'(字符)和 "hello"(字符串)。不进行类型转换就混合不兼容类型会导致错误或意外结果。

    Data Type Example Literal Significance
    Integer 42, -7 Whole numbers, no fractional part
    Real / Float 3.14, -0.5 Numbers with decimal points
    Boolean True, False Only two possible values
    Character ‘A’, ‘7’ Single symbol in single quotes
    String “hello”, “123” Sequence of characters

    Remember that the character '7' is not the same as the integer 7. The character is a symbol; the integer is a numeric quantity. This distinction is tested in Edexcel programming questions.

    记住字符 '7' 与整数 7 不同。字符是符号,整数是数值量

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Operators and Expressions in A-Level Programming | A-Level 编程中的运算符与表达式

    📚 Operators and Expressions in A-Level Programming | A-Level 编程中的运算符与表达式

    Programming revolves around processing data, and operators are the building blocks that let us transform and compare that data. This article covers the operator types, precedence rules, truth tables, and common exam pitfalls required by the Edexcel A-Level Computer Science specification.

    编程围绕数据处理展开,而运算符是让我们能够转换和比较数据的基本构件。本文涵盖 Edexcel A-Level 计算机科学大纲要求的运算符类型、优先级规则、真值表和常见考试陷阱。

    1. Operator Categories | 运算符分类

    An operator is a symbol or keyword that performs an operation on one or more operands. For example, in the expression a + b, + is the operator and a, b are operands. Operators can be unary, binary, or ternary depending on the number of operands they take.

    运算符是对一个或多个操作数执行操作的符号或关键字。例如,在表达式 a + b 中,+ 是运算符,a、b 是操作数。根据操作数的数量,运算符可以是一元、二元或三元运算符。

    The main operator categories tested in Edexcel A-Level Computer Science are arithmetic, comparison, logical, bitwise, assignment, and string operators. Each category has its own rules, and mixing them often causes errors in exam answers.

    Edexcel A-Level 计算机科学考查的主要运算符类别包括算术、比较、逻辑、位、赋值和字符串运算符。每个类别都有自己的规则,混用它们常常会导致考试答案出错。


    2. Arithmetic Operators | 算术运算符

    Arithmetic operators perform standard mathematical calculations. The most common ones are addition (+), subtraction (-), multiplication (*), division (/), integer division (DIV), and modulo (MOD). In pseudocode, Edexcel often uses DIV and MOD; in Python, integer division is // and modulo is %.

    算术运算符执行标准数学计算。最常见的有加(+)、减(-)、乘(*)、除(/)、整除(DIV)和取模(MOD)。在伪代码中,Edexcel 常用 DIV 和 MOD;在 Python 中,整除是 //,取模是 %。

    Operator Meaning Example Result
    + Addition 7 + 2 9
    Subtraction 7 – 2 5
    * Multiplication 7 * 2 14
    / Division 7 / 2 3.5
    DIV Integer division 7 DIV 2 3
    MOD Modulo 7 MOD 2 1

    In arithmetic expressions, the data types of operands matter. If both operands are integers, integer division may be used automatically in some languages, while division always produces a real result in others.

    在算术表达式中,操作数的数据类型非常重要。如果两个操作数都是整数,某些语言可能会自动使用整除,而在其他语言中除法总是产生实数结果。


    3. Division, Integer Division and Modulo | 除法、整除与取模

    Division can be ordinary division returning a real number, or integer division returning the whole-number quotient without the remainder. Modulo returns the remainder. These are essential for problems involving digit extraction, even/odd checks, and cyclic indexing.

    除法可以是返回实数的普通除法,也可以是返回整数商且不含余数的整除。取模返回余数。这些在涉及数字提取、奇偶判断和循环索引的问题中至关重要。

    In many algorithms, DIV and MOD are used together. For a two-digit integer n, the tens digit is n DIV 10 and the units digit is n MOD 10. For example, 57 DIV 10 = 5 and 57 MOD 10 = 7.

    在许多算法中,DIV 和 MOD 一起使用。对于一个两位整数 n,十位数字是 n DIV 10,个位数字是 n MOD 10。例如,57 DIV 10 = 5,57 MOD 10 = 7。

    A common exam task checks whether a number is even: if n MOD 2 = 0 then the number is even; otherwise it is odd. This condition must use MOD, not division, because division would give a real quotient.

    常见的考试任务是检查一个数是否为偶数:如果 n MOD 2 = 0,则该数为偶数;否则为奇数。该条件必须使用 MOD,而不是除法,因为除法会得到实数商。


    4. Comparison / Relational Operators | 比较 / 关系运算符

    Comparison operators compare two values and return a Boolean result (TRUE or FALSE). The standard set includes equal to (= or ==), not equal to (≠ or !=), greater than (>), less than (<), greater than or equal to (≥ or >=), and less than or equal to (≤ or <=).

    比较运算符比较两个值并返回布尔结果(TRUE 或 FALSE)。标准集合包括等于(= 或 ==)、不等于(≠ 或 !=)、大于(>)、小于(<)、大于等于(≥ 或 >=)和小于等于(≤ 或 <=)。

    A single ‘=’ in many languages is assignment, while ‘==’ is comparison, a common exam trap. In Edexcel pseudocode, comparison often uses ‘=’ and assignment uses ‘←’, so the context makes the meaning clear.

    在许多语言中,单个 ‘=’ 是赋值,而 ‘==’ 是比较,这是一个常见的考试陷阱。在 Edexcel 伪代码中,比较常使用 ‘=’,赋值使用 ‘←’,因此上下文使含义清晰。

    Comparison expressions are used in selection and iteration statements. For example, IF score >= 80 THEN grade ← ‘A’. The result is always a Boolean value. Be careful to use ‘=’ or ‘==’ consistently as specified by the question.

    比较表达式用于选择和迭代语句。例如,IF score >= 80 THEN grade ← ‘A’。结果始终是布尔值。注意按照题目要求一致使用 ‘

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Programming Techniques: Operators, Control Flow and Functions | 编程技术:运算符、控制流与函数

    📚 Programming Techniques: Operators, Control Flow and Functions | 编程技术:运算符、控制流与函数

    In Edexcel A Level Computer Science, programming questions assess more than remembering syntax: they test your ability to read, trace and design algorithms using exam pseudocode, Python or another high-level language. This guide brings together operators, control structures, subprograms, recursion and algorithm efficiency in a focused revision format.

    在 Edexcel A Level 计算机科学中,编程题考查的不只是记住语法:它们测试你使用考试伪代码、Python 或其他高级语言阅读、跟踪和设计算法的能力。本指南以集中复习的形式,汇总运算符、控制结构、子程序、递归和算法效率。


    1. Operators and Expressions | 运算符与表达式

    Operators are the building blocks of expressions. In Edexcel pseudocode, you are expected to know arithmetic operators (+ – * / MOD DIV), comparison operators (= ≠ < > ≤ ≥) and logical operators (AND OR NOT).

    运算符是表达式的基本构件。在 Edexcel 伪代码中,你需要掌握算术运算符(+ – * / MOD DIV)、比较运算符(= ≠ < > ≤ ≥)以及逻辑运算符(AND OR NOT)。

    The integer division operator DIV returns the whole-number quotient, while MOD returns the remainder. For example, 17 DIV 5 = 3 and 17 MOD 5 = 2.

    整数除法运算符 DIV 返回整数商,而 MOD 返回余数。例如,17 DIV 5 = 3,17 MOD 5 = 2。

    更多咨询请联系16621398022(同微信)

  • Programming Languages: Paradigms and Translation | 编程语言:范式与翻译

    📚 Programming Languages: Paradigms and Translation | 编程语言:范式与翻译

    Programming languages are the bridge between human problem solving and machine execution. In Edexcel A Level Computer Science, candidates must compare language types, explain common paradigms, and describe how source code is translated into executable form. This revision guide covers low-level and high-level languages, the main programming paradigms, translation tools, and debugging techniques.

    编程语言是人类问题求解与机器执行之间的桥梁。在 Edexcel A Level 计算机科学中,考生需要比较语言类型、解释常见编程范式,并描述源代码如何被翻译为可执行形式。本复习指南涵盖低级语言与高级语言、主要编程范式、翻译工具和调试技术。

    1. Low-Level and High-Level Languages | 低级语言与高级语言

    Low-level languages are close to hardware and give direct control over memory and processor registers. High-level languages are closer to human language and use abstraction, making programs easier to read, write and maintain.

    低级语言接近硬件,可直接控制内存和处理器寄存器。高级语言更接近人类语言并使用抽象,使程序更易读、易写、易维护。

    Low-level languages offer fast execution and precise control, which is useful for embedded systems and device drivers. However, they are difficult to debug and not portable across different processor families. High-level languages improve productivity and portability, but their source code must be translated before it can run.

    低级语言执行速度快、控制精确,适用于嵌入式系统和设备驱动程序。然而它们难以调试,并且不能在多种处理器系列之间移植。高级语言提高了开发效率和可移植性,但其源代码必须经过翻译后才能运行。

    • Low-level languages: machine code and assembly are processor-specific and require detailed hardware knowledge.
    • 低级语言:机器码和汇编语言面向特定处理器,需要详细的硬件知识。
    • High-level languages: Python, Java, C# and Visual Basic allow portable source code across platforms with suitable translators.
    • 高级语言:Python、Java、C# 和 Visual Basic 可在合适的翻译器支持下跨平台移植源代码。

    2. Machine Code and Assembly Language | 机器码与汇编语言

    Machine code consists of binary instructions that a CPU can execute directly. Each instruction has an opcode and often an operand, stored as patterns such as 10110000 01100001. Assembly language uses mnemonics such as LDA, ADD, STA and machine-specific operands, which an assembler converts into machine code.

    机器码由 CPU 可直接执行的二进制指令组成。每条指令包含操作码和通常的操作数,以 10110000 01100001 等模式存储。汇编语言使用 LDA、ADD、STA 等助记符和机器特定的操作数,汇编器将其转换为机器码。

    One assembly instruction usually maps to one machine instruction, giving fast execution but long development time. Programs written for one architecture, such as x86, will not run directly on another, such as ARM.

    一条汇编指令通常对应一条机器指令,因此执行速度快,但开发时间长。为某一架构(如 x86)编写的程序无法直接在另一架构(如 ARM)上运行。

    • Machine code uses binary opcodes and operands understood directly by the control unit.
    • 机器码使用二进制操作码和操作数,由控制单元直接理解。
    • Assembly language improves readability through mnemonics but still requires knowledge of registers and memory addressing.
    • 汇编语言通过助记符提高了可读性,但仍需了解寄存器和内存寻址知识。

    3. Imperative and Procedural Paradigms | 命令式与过程式范式

    The imperative paradigm focuses on describing how a task is completed using sequences, selection and iteration. Procedural programming builds on this by organising code into procedures, functions or subroutines that can be called with parameters and return values.

    命令式范式侧重于通过顺序、选择和迭代描述任务如何完成。过程式编程在此基础上将代码组织为过程、函数或子程序,可通过参数调用并返回值。

    Procedural languages encourage modularity, reuse and stepwise refinement. Local and global variables must be managed carefully to avoid unintended side effects. Breaking a large problem into smaller procedures also makes testing and maintenance easier.

    过程式语言鼓励模块化、代码复用和逐步求精。必须谨慎管理局部变量和全局变量,以避免意外的副作用。将大型问题拆分为较小的过程也使得测试和维护更加容易。

    subtotal = quantity × price  →  total = subtotal + tax  →  output total

    示例:先计算小计,再计算含税总额,最后输出结果。


    4. Object-Oriented Programming | 面向对象编程

    Object-oriented programming (OOP) models real-world or abstract entities as classes and objects. A class defines attributes and methods; objects are instances created from a class. Key principles include encapsulation, inheritance, polymorphism and abstraction.

    面向对象编程将现实世界或抽象实体建模为类和对象。类定义属性和方法,对象是由类创建的实例。关键原则包括封装、继承、多态和抽象。

    Encapsulation means data and methods are bundled together, and access is controlled through interfaces. Inheritance allows a subclass to reuse and extend the behaviour of a parent class. Polymorphism means the same method name can behave differently depending on the object type.

    封装意味着数据和方法捆绑在一起,通过接口控制访问。继承允许子类复用并扩展父类的行为。多态意味着同一方法名可根据对象类型表现出不同行为

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Techniques and Algorithms | Edexcel A-Level 编程:核心技术与算法

    📚 Edexcel A-Level Programming: Core Techniques and Algorithms | Edexcel A-Level 编程:核心技术与算法

    Programming is at the heart of the Edexcel A-Level Computer Science course. This article consolidates the core techniques you must be able to read, write, trace, and debug: data types, control flow, arrays, subroutines, recursion, file handling, and searching and sorting algorithms.

    编程是 Edexcel A-Level 计算机科学课程的核心。本文整合了你必须能够阅读、编写、跟踪和调试的核心技术:数据类型、控制流、数组、子程序、递归、文件处理以及查找和排序算法。

    Each section gives you the key ideas in clear pseudocode style, with paired English and Chinese explanations so you can revise actively and apply the techniques under exam conditions.

    每一节都以清晰的伪代码风格给出关键思想,并配有英文和中文对照解释,让你能够在考试条件下主动复习并应用这些技术。


    1. Programming Fundamentals and Data Types | 编程基础与数据类型

    Every program manipulates data, and Edexcel expects you to recognise primitive data types: integer, real/float, Boolean, character, and string. You should also know how to declare them in pseudocode and how type errors occur.

    每个程序都操作数据,Edexcel 要求你识别基本数据类型:整数、实数/浮点数、布尔、字符和字符串。你还需要知道如何在伪代码中声明它们以及类型错误是如何发生的。

    Use INTEGER for whole numbers, REAL for decimals, BOOLEAN for TRUE/FALSE values, CHAR for one character, and STRING for sequences of characters. Type compatibility matters when comparing or assigning values.

    整数用 INTEGER,小数用 REAL,真/假值用 BOOLEAN,单个字符用 CHAR,字符序列用 STRING。在比较或赋值时,类型兼容性非常重要。

    For example, assigning a real value to an integer variable without conversion may cause data loss or a type error. Edexcel pseudocode usually requires explicit type in declarations such as DECLARE age : INTEGER.

    例如,在不进行转换的情况下将实数值赋给整数变量可能会导致数据丢失或类型错误。Edexcel 伪代码通常要求在声明中明确类型,例如 DECLARE age : INTEGER


    2. Variables, Constants, and Scope | 变量、常量与作用域

    Variables store values that can change during execution, while constants hold fixed values. In pseudocode, declare constants with CONST and variables with a type. Scope refers to where an identifier is accessible: local variables exist inside a procedure, whereas global variables can be accessed throughout the program.

    变量存储在执行过程中可改变的值,而常量保存固定的值。在伪代码中,用 CONST 声明常量,用类型声明变量。作用域指标识符可以访问的位置:局部变量存在于过程内部,而全局变量可被整个程序访问。

    Using global variables excessively makes debugging harder and can introduce side effects. Edexcel code often uses parameter passing instead of relying on globals.

    过度使用全局变量会给调试带来困难,并可能引入副作用。Edexcel 代码通常使用参数传递而不是依赖全局变量。

    Always initialise variables before use. The scope of a loop variable, for example FOR i ← 1 TO 10, is normally limited to the loop block in pseudocode.

    始终在使用变量之前初始化它们。循环变量的作用域,例如 FOR i ← 1 TO 10,在伪代码中通常仅限于循环块内。


    3. Operators and Expressions | 运算符与表达式

    Arithmetic operators such as +, -, ×, ÷, MOD, DIV, and exponentiation ^ are used to build expressions. Relational operators (=, ≠, <, >, ≤, ≥) compare values and return Boolean results. Logical operators AND, OR, NOT combine Boolean expressions.

    算术运算符如 +、-、×、÷、MOD、DIV 和指数运算 ^ 用于构造表达式。关系运算符(=、≠、<、>、≤、≥)比较值并返回布尔结果。逻辑运算符 AND、OR、NOT 组合布尔表达式。

    Operator precedence is essential: brackets first, then exponentiation, multiplication/division, integer division/mod, addition/subtraction, then relational and logical operators. Use brackets to make expressions clear and avoid ambiguity.

    运算符优先级很重要:先括号,再指数,再乘除,再整数除法/取模,再加减,最后是关系和逻辑运算符。使用括号使表达式清晰并避免歧义。

    Example: (3 + 2) × 4 DIV 2 – 1 = 9

    示例:(3 + 2) × 4 DIV 2 – 1 = 9


    4. Selection: IF and CASE | 选择结构:IF 与 CASE

    Selection allows a program to take different paths. The IF statement tests a condition and executes a block when true; ELSE is optional. Nested IF statements can handle multiple conditions but can become hard to read.

    选择结构允许程序采取不同路径。IF 语句测试条件,当条件为真时执行代码块;ELSE 可选。嵌套 IF 可以处理多个条件,但可读性可能变差。

    The CASE statement is neater for several mutually exclusive values: CASE OF item: value1 → action1; value2 → action2; OTHERWISE → default; ENDCASE.

    对于多个互斥的值,CASE 语句更简洁:CASE OF item: 值1 → 操作1;值2 → 操作2;OTHERWISE → 默认;ENDCASE

    Always test selection with boundary values just above and below the threshold, because programming errors often occur at the exact boundary of a condition such as IF score > 60.

    始终使用恰好高于和低于阈值的边界值测试选择结构,因为编程错误通常发生在条件的精确边界处,例如 IF score > 60


    5. Iteration: FOR, WHILE, REPEAT | 迭代:FOR、WHILE、REPEAT

    Iteration repeats code. A count-controlled loop uses FOR: FOR i ← 1 TO 10 ... ENDFOR. The loop variable must not be modified inside the loop.

    迭代重复执行代码。计数控制循环使用 FOR:FOR i ← 1 TO 10 ... ENDFOR。循环变量不能在循环内部被修改。

    Condition-controlled loops include WHILE (test at top) and REPEAT…UNTIL (test at bottom). WHILE may not execute if the condition is false initially; REPEAT always executes at least once.

    条件控制循环包括 WHILE(顶部测试)和 REPEAT…UNTIL(底部测试)。如果初始条件为假,WHILE 可能不执行;REPEAT 至少执行一次。

    Choose the correct loop for the problem; using the wrong type often causes logic errors such as infinite loops or off-by-one errors. Trace tables help you check loop termination.

    为问题选择正确的循环类型;使用错误的类型通常会导致逻辑错误,如无限循环或差一错误。跟踪表可帮助你检查循环终止。


    6. Arrays and Lists | 数组与列表

    Arrays store multiple elements of the same data type under one identifier, using an index. In pseudocode, DECLARE scores : ARRAY[1:10] OF INTEGER creates a one-dimensional array with indices 1 to 10.

    数组在同一个标识符下存储多个相同数据类型的元素,使用索引访问。在伪代码中,DECLARE scores : ARRAY[1:10] OF INTEGER 创建一个索引为 1 到 10 的一维数组。

    Two-dimensional arrays are useful for grids or tables. You must be able to traverse arrays using loops, find highest/lowest, sum elements, and swap values.

    二维数组对于网格或表格很有用。你必须能够使用循环遍历数组、查找最高/最低值、求和以及交换值。

    • One-dimensional access: scores[3]一维访问:scores[3]
    • Two-dimensional access: grid[row, column]二维访问:grid[row, column]

    7. String Handling | 字符串处理

    String manipulation occurs in many Edexcel questions: concatenation with + or &, length functions, substring extraction, character access, and case conversion. You may be asked to trace pseudocode that builds or modifies strings.

    字符串操作出现在许多 Edexcel 题目中:使用 + 或 & 进行连接、长度函数、子串提取、字符访问和大小写转换。你可能会被要求跟踪构建或修改字符串的伪代码。

    A common task is to check if a string is a palindrome or to remove vowels. Make sure you can iterate character by character and build a new string.

    常见任务是检查字符串是否为回文

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Constructs, Data Structures and Algorithms | Edexcel A-Level 编程:核心结构、数据结构与算法

    📚 Edexcel A-Level Programming: Core Constructs, Data Structures and Algorithms | Edexcel A-Level 编程:核心结构、数据结构与算法

    In Edexcel A-Level Computer Science, programming is not just about writing code; it is about developing computational thinking, selecting appropriate data structures and algorithms, and evaluating efficiency and correctness. This article reviews the core programming concepts assessed in the specification, from basic constructs and data structures to searching, sorting, recursion, Big O notation and object-oriented programming.

    在 Edexcel A-Level 计算机科学中,编程不仅是写代码,更是发展计算思维、选择合适的数据结构和算法,并评估效率与正确性。本文回顾考试大纲中评估的核心编程概念,从基本结构、数据结构到查找、排序、递归、大 O 表示法和面向对象编程。


    1. Programming Constructs: Sequence, Selection, Iteration | 程序结构:顺序、选择、迭代

    Every imperative program is built from three control constructs: sequence, selection (if, else, switch/case) and iteration (for, while, repeat-until). Sequence executes statements one after another; selection chooses between paths based on Boolean conditions; iteration repeats a block while a condition is true or for a fixed number of times.

    每个命令式程序都由三种控制结构组成:顺序、选择(if、else、switch/case)和迭代(for、while、repeat-until)。顺序让语句依次执行;选择根据布尔条件在不同路径间选择;迭代在条件为真或固定次数内重复某一代码块。

    Nested constructs are allowed, so an if can appear inside a loop, and a loop can appear inside another loop. Correct indentation and consistent use of logical conditions make nested constructs easier to trace during an exam.

    嵌套结构是允许的,因此 if 可以出现在循环内部,循环也可以出现在另一个循环内部。正确的缩进和一致的逻辑条件使用可使嵌套结构在考试中更容易跟踪。


    2. Data Types, Variables and Operators | 数据类型、变量与运算符

    Primitive data types include integer, real/float, Boolean, character and string. Variables have an identifier, type and value; constants are declared once and cannot be modified. Operators enable arithmetic (+, -, *, /, MOD, DIV), comparison (=, <, >, <=, >=, <>) and logic (AND, OR, NOT).

    基本数据类型包括整型、实数/浮点型、布尔型、字符型和字符串。变量由标识符、类型和值组成;常量一经声明不可修改。运算符支持算术运算(+、-、*、/、MOD、DIV)、比较运算(=、<、>、<=、>=、<>)和逻辑运算(AND、OR、NOT)。

    Operator precedence determines the order of evaluation. In many languages NOT is evaluated before AND, and AND before OR. Parentheses should be used to make complex expressions unambiguous and to reduce logic errors.

    运算符优先级决定求值顺序。在许多语言中 NOT 先于 AND 求值,AND 先于 OR。应使用括号使复杂表达式无歧义并减少逻辑错误。


    3. Arrays and Lists | 数组与列表

    Arrays store a fixed number of elements of the same data type, and elements are accessed by an index, usually starting from 0. Lists or dynamic arrays can grow and shrink, allowing insertion and deletion. Two-dimensional arrays represent tables and grids, such as a chessboard or spreadsheet.

    数组存储固定数量且类型相同的元素,通过下标访问,下标通常从 0 开始。列表或动态数组可增长和收缩,支持插入和删除。二维数组用于表示表格和网格,如棋盘或电子表格。

    Common array operations include traversal with a loop, searching for a value, updating an element, and calculating aggregate values such as sum, minimum and maximum. Bounds checking is essential because accessing an index outside the valid range causes an error.

    常见数组操作包括使用循环遍历、查找值、更新元素以及计算总和、最小值和最大值等聚合值。边界检查非常重要,因为访问超出有效范围的下标会导致错误。


    4. Stacks and Queues | 栈与队列

    A stack follows LIFO (Last In First Out) behaviour; operations push, pop and peek. A queue follows FIFO (First In First Out) behaviour; operations enqueue and dequeue. Stacks support recursion, undo features and expression evaluation; queues are used in print spooling and CPU scheduling.

    栈遵循后进先出(LIFO)规则;操作包括入栈、出栈和查看栈顶。队列遵循先进先出(FIFO)规则;操作包括入队和出队。栈支持递归、撤销功能和表达式求值;队列用于打印假脱机和 CPU 调度。

    Both structures can be implemented using arrays or linked lists. In an array-based stack, a pointer tracks the top; in an array-based queue, front and rear pointers are needed to avoid shifting all elements after each dequeue.

    两种结构都可以用数组或链表实现。在基于数组的栈中,一个指针跟踪栈顶;在基于数组的队列中,需要 front 和 rear 指针,以避免每次出队时移动所有元素。


    5. Linear and Binary Search | 线性查找与二分查找

    Linear search scans each element from the start until the target is found or the list ends. It works on unsorted data and has average time O(n). Binary search works only on sorted data: examine the middle element, then discard half of the remaining range. Binary search has time O(log n), requiring far fewer comparisons for large n.

    线性查找从开头逐个扫描元素,直到找到目标或列表结束。它适用于未排序数据,平均时间复杂度为 O(n)。二分查找仅适用于有序数据:检查中间元素,然后舍弃剩余范围的一半。二分查找时间复杂度为 O(log n),对于大数据量比较次数少得多。

    Binary search: O(log n) vs linear search: O(n)

    When the data is sorted and no insertions or deletions occur often, binary search is preferred. If the data is frequently updated, linear search may be simpler because maintaining sorted order adds overhead.

    当数据已排序且不经常插入或删除时,优先使用二分查找。如果数据频繁更新,线性查找可能更简单,因为维护有序状态会增加额外开销。


    6. Bubble, Insertion and Merge Sort | 冒泡、插入与归并排序

    Bubble sort compares adjacent pairs and swaps if out of order; after each pass, the largest unsorted element ‘bubbles’ to its correct position. Insertion sort builds a sorted sublist by taking the next element and inserting it into the correct position. Merge sort uses divide and conquer: split the list into halves, sort each recursively, then merge the two sorted halves.

    冒泡排序比较相邻元素并交换逆序对;每轮过后,未排序部分中的最大元素 “冒泡” 到正确位置。插入排序通过取出下一个元素并将其插入已排序子列表的正确位置来构建有序结果。归并排序采用分治策略:将列表分成两半,分别递归排序,然后合并两个有序子列表。

    Algorithm Best Average Worst Stable?
    Bubble sort O(n) O(n²) O(n²) Yes
    Insertion sort O(n) O(n²) O(n²) Yes
    Merge sort O(n log n) O(n log n) O(n log n) Yes

    7. Recursion and the Call Stack | 递归与调用栈

    A recursive subroutine calls itself with a smaller or simpler input. Every recursion must have a base case that stops the calls, otherwise infinite recursion causes a stack overflow. The call stack stores return addresses, parameters and local variables for each active call.

    递归子程序用更小或更简单的输入调用自身。每次递归必须有一个基本情况来停止调用,否则无限递归会导致栈溢出。调用栈为每个活跃调用存储返回地址、参数和局部变量。

    A classic example is factorial: factorial(n) = n × factorial(n-1) with factorial(0) = 1. Each recursive call pushes a new frame onto the stack; when the base case is reached, the frames pop off and return values multiply together.

    经典示例是阶乘:factorial(n) = n × factorial(n-1),且 factorial(0) = 1。每次递归调用将一个新帧压入栈中;到达基本情况后,这些帧弹出,返回值依次相乘。

    factorial(n) = n × factorial(n-1), factorial(0) = 1


    8. Big O Notation and Efficiency | 大 O 表示法与效率

    Big O notation gives an upper bound for how time or space grows with input size n. Common classes are O(1), O(log n), O(n), O(n log n), O(n²) and O(2ⁿ). When analysing an algorithm, focus on the dominant term and ignore constants and lower-order terms.

    大 O 表示法给出时间或空间随输入规模 n 增长的上界。常见类别有 O(1)、O(log n)、O(n)、O(n log n)、O(n²) 和 O(2ⁿ)。分析算法时,关注主导项,忽略常数和低阶项。

    Dominant term: 3n² + 5n + 2 = O(n²)

    For example, a loop that visits every element once is O(n); two nested loops over the same array are O(n²). Space complexity is analysed in the same way, measuring additional memory used by an algorithm.

    例如,访问每个元素一次的循环是 O(n);对同一数组进行两个嵌套循环则是 O(n²)。空间复杂度以相同方式分析,衡量算法使用的额外内存。


    9. Object-Oriented Programming Basics | 面向对象编程基础

    Object-oriented programming organises code around classes and objects. A class is a blueprint with attributes and methods; an object is an instance. Encapsulation hides internal state behind an interface; inheritance allows a subclass to extend a superclass; polymorphism lets different classes respond to the same method call in their own way.

    面向对象编程围绕类和对象组织代码。类是包含属性和方法的蓝图;对象是类的实例。封装将内部状态隐藏在接口之后;继承允许子类扩展父类;多态让不同类以各自方式响应同一方法调用。

    These principles improve maintainability and reuse. For example, a superclass Vehicle can have method move(), while subclasses Car and Bicycle override move() with specific behaviour, demonstrating polymorphism.

    这些原则提高了可维护性和复用性。例如,父类 Vehicle 可以有方法 move(),而子类 Car 和 Bicycle 用特定行为重写 move(),这就是多态。


    10. Testing, Debugging and Trace Tables | 测试、调试

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming Essentials: Constructs, Data Structures and Algorithms | Edexcel A-Level 编程精讲:结构、数据结构与算法

    📚 Edexcel A-Level Programming Essentials: Constructs, Data Structures and Algorithms | Edexcel A-Level 编程精讲:结构、数据结构与算法

    Programming in Edexcel A-Level Computer Science is assessed through Problem Solving with Programming topics and a practical project. This revision guide explains the core constructs, data structures, algorithmic techniques and exam-style thinking you need to score confidently. It is designed for the Edexcel 9BS0 specification but is useful for any A-Level programming paper.

    Edexcel A-Level 计算机科学中的编程部分通过“编程问题解决”主题和实践项目进行考核。本复习指南讲解核心结构、数据结构、算法思维以及考试所需的解题方法。内容针对 Edexcel 9BS0 大纲,也适用于任何 A-Level 编程试卷。

    1. Computational Thinking and Problem Decomposition | 计算思维与问题分解

    Before writing code, an A-Level programmer must break a problem into smaller, manageable parts. Decomposition means splitting a large task such as ‘manage a library loan system’ into modules like borrower records, book stock, overdue calculation and reporting.

    在编写代码之前,A-Level 程序员必须把问题拆分为更小、可管理的部分。分解是指把“管理图书馆借阅系统”这样的大任务拆分为借阅人记录、图书库存、逾期计算和报告等模块。

    Pattern recognition identifies similarities with problems you have already solved, such as realising that finding the oldest borrower is the same as finding a maximum value. Abstraction removes unnecessary detail so you focus on the data and operations that matter for the solution.

    模式识别找出与已解决问题的相似之处,例如意识到查找最早借阅人与查找最大值是同一类问题。抽象则是去掉不必要的细节,让你专注于对解决方案重要的数据和操作。


    2. Sequence, Selection and Iteration | 顺序、选择与迭代

    All structured programs are built from three fundamental constructs: sequence, selection and iteration. Sequence executes instructions in the order they are written; assignment of a variable then output of its value is a simple example.

    所有结构化程序都由三种基本结构组成:顺序、选择和迭代。顺序结构按照代码编写顺序执行指令;先给变量赋值再输出其值就是一个简单例子。

    Selection uses if, elif and else to choose between branches based on a Boolean condition. For example, if temperature > 30 then print “Heat warning” else print “Normal”. Iteration repeats a block using for loops for counted repetition and while loops for condition-controlled repetition.

    选择结构使用 if、elif 和 else 根据布尔条件在不同分支之间进行选择。例如,如果 temperature > 30,就输出 “Heat warning”,否则输出 “Normal”。迭代结构使用 for 循环进行计数重复,使用 while 循环进行条件控制重复。

    total ← total + number

    This accumulation pattern is common in exam trace-table questions, so update one row per pass and record every variable change.

    这种累加模式在考试跟踪表问题中很常见,因此每次循环应更新一行,并记录每个变量的变化。


    3. Data Types, Variables and Constants | 数据类型、变量与常量

    Python uses dynamic typing, but Edexcel pseudocode expects you to know integer, real or float, Boolean, character and string. Choosing the correct type affects operations; you cannot logically add a string “12” to an integer 12 without casting.

    Python 使用动态类型,但 Edexcel 伪代码要求你掌握整型、实型或浮点型、布尔型、字符型和字符串。选择正确的类型会影响运算;如果不进行类型转换,你不能把字符串 “12” 与整数 12 直接相加。

    Constants are named values that do not change during execution, such as VAT_RATE = 0.20. Variables hold values that can change, and identifiers should be meaningful. Use camelCase or underscores consistently in your project write-up.

    常量是在程序执行过程中不变的命名值,例如 VAT_RATE = 0.20。变量保存可以改变的值,标识符应具有意义。在项目报告中应统一使用 camelCase 或下划线命名方式。


    4. Data Structures: Arrays, Lists and Records | 数据结构:数组、列表与记录

    A one-dimensional array stores elements of the same type in contiguous memory. In Python, lists are more flexible: they can hold mixed types, are dynamic, and provide built-in methods such as append, pop, sort and reverse.

    一维数组在连续内存中存储相同类型的元素。在 Python 中,列表更加灵活:可以存放混合类型,大小动态变化,并提供 append、pop、sort 和 reverse 等内置方法。

    A two-dimensional array is often visualised as a grid with row and column indices. A record is a composite structure that groups fields of different types, for example a Student record with name, age and tutor group. In Python a dictionary or class can represent a record.

    二维数组通常可以可视化为带有行索引和列索引的网格。记录是一种复合结构,将不同类型的字段组合在一起,例如包含姓名、年龄和导师组的 Student 记录。在 Python 中,可以用字典或类来表示记录。


    5. Stacks, Queues and Linked Lists | 栈、队列与链表

    A stack is a Last In First Out (LIFO) structure. The main operations are push to add an item to the top and pop to remove the top item. A queue is First In First Out (FIFO), using enqueue at the rear and dequeue from the front.

    栈是一种后进先出(LIFO)结构。主要操作是 push 将一个元素添加到栈顶,pop 移除栈顶元素。队列是先进先出(FIFO)结构,在队尾执行 enqueue,在队头执行 dequeue。

    Stacks support recursion, undo features and backtracking; queues model print spools and CPU scheduling. A linked list is a dynamic structure where each node holds data and a pointer to the next node, allowing efficient insertion and deletion without shifting elements.

    栈支持递归、撤销功能和回溯;队列用于模拟打印队列和 CPU 调度。链表是一种动态结构,每个节点包含数据和指向下一个节点的指针,因此无需移动元素即可高效插入和删除。


    6. Functions, Procedures and Parameter Passing | 函数、过程与参数传递

    A function returns a value using return; a procedure performs an action without returning a value. Both help reuse code and reduce duplication. Parameters allow data to be passed into subprograms.

    函数使用 return 返回一个值;过程执行某个动作但不返回值。两者都有助于重用代码、减少重复。参数允许将数据传递给子程序。

    Parameter passing by value copies the data, so changes inside the subprogram do not affect the original variable; passing by reference gives the subprogram access to the original memory location. In Python, integers and strings behave like passed by value, while lists are passed by reference.

    按值传递参数会复制数据,因此子程序内部的修改不会影响原变量;按引用传递则允许子程序访问原内存位置。在 Python 中,整数和字符串的行为类似于按值传递,而列表则是按引用传递。


    7. Searching and Sorting Algorithms | 查找与排序算法

    Linear search checks every element in sequence until the target is found or the end is reached. It works on unsorted data and has O(n) worst-case time complexity.

    线性查找按顺序检查每个元素,直到找到目标或到达末尾。它适用于未排序数据,最坏时间复杂度为 O(n)。

    Binary search requires sorted data. It repeatedly compares the middle element, discarding half the remaining items each time. Its worst-case time complexity is O(log n).

    二分查找要求数据已排序。它反复比较中间元素,每次排除剩余元素的一半。最坏时间复杂度为 O(log n)。

    Binary search worst case: O(log₂ n)

    Bubble sort passes through the list, swapping adjacent items that are out of order. It is simple but has O(n²) time complexity. Merge sort uses divide and conquer, splitting the list and merging sorted sublists, giving O(n log n).

    冒泡排序遍历列表,交换相邻的乱序元素。它实现简单,但时间复杂度为 O(n²)。归并排序使用分治策略,先拆分列表再合并有序子列表,时间复杂度为 O(n log n)。


    8. Recursion and Algorithm Trace Tables | 递归与算法跟踪表

    A recursive subroutine calls itself with a smaller or simpler input until it reaches a base case. For example, factorial n = n × factorial(n-1), with base case factorial(0)=1.

    递归子程序使用更小或更简单的输入调用自身,直到达到基准情形。例如,阶乘 n = n × factorial(n-1),基准情形为 factorial(0)=1。

    n! = n × (n – 1)! for n > 0; 0! = 1

    Recursion produces elegant solutions for tree traversal, backtracking and divide-and-conquer algorithms, but it uses stack memory and can be less efficient than iteration if many recursive calls are made. Always identify the base case in exam questions.

    递归为树的遍历、回溯和分治算法提供了简洁的解决方案,但它会占用栈内存,如果递归调用过多可能不如迭代高效。在考试题中一定要识别基准情形。


    9. File Handling, Validation and Exception Handling | 文件处理、验证与异常处理

    Programs often read from and write to text or CSV files. Use open, read/write and close operations correctly; with statements in Python manage resource closure safely. Always check that a file exists before reading to avoid runtime errors.

    程序经常需要读写文本文件或 CSV 文件。应正确使用 open、read/write 和 close 操作;Python 中的 with 语句可以安全地管理资源关闭。读取前应始终检查文件是否存在,以避免运行时错误。

    Validation checks data against a rule before processing: type check, range check, presence check, format check and length check. Exception handling uses try/except to catch errors such as ValueError, FileNotFoundError and ZeroDivisionError, preventing the program from crashing.

    验证是在处理前根据规则检查数据:类型检查、范围检查、存在性检查、格式检查和长度检查。异常处理使用 try/except 捕获 ValueError、FileNotFoundError 和 ZeroDivisionError 等错误,防止程序崩溃。


    10. Object-Oriented Programming Essentials | 面向对象编程基础

    A class is a blueprint; an object is an instance. Encapsulation bundles data fields and methods, protecting internal state. In Python, __init__ is the constructor and self refers to the current object.

    类是蓝图;对象是实例。封装将数据字段和方法绑定在一起,保护内部状态。在 Python 中,__init__ 是构造方法,self 指向当前对象。

    Inheritance allows a child class to reuse and extend parent attributes and methods, reducing duplication. Polymorphism lets different classes respond to the same method name in their own way, useful for exam questions on OOP principles.

    继承允许子类重用并扩展父类的属性和方法,减少重复。多态让不同的类以自己的方式响应相同的方法名,在考查面向对象原则的题目中非常有用。


    11. Testing, Debugging and Integrated Environments | 测试、调试与集成开发环境

    You must test normal, boundary and erroneous data. Boundary testing checks values at the edge of valid ranges, such as 0, 1, 100 and 101 for a mark between 1 and 100. Erroneous tests use wrong types or empty inputs.

    你必须测试正常数据、边界数据和错误数据。边界测试检查有效范围边缘的值,例如分数在 1 到 100 之间时测试 0、1、100 和 101。错误测试使用错误类型或空输入。

    Debugging tools include breakpoints, step into/over, watch expressions and stack traces. An IDE integrates an editor, run-time environment, debugger and version control; using these features improves the reliability of your A-Level project.

    调试工具包括断点、单步进入/跳过、监视表达式和堆栈跟踪。集成开发环境(IDE)集成了编辑器、运行环境、调试器和版本控制;使用这些功能可以提高 A-Level 项目的可靠性。


    12. Exam Technique and Common Pitfalls | 考试技巧与常见误区

    In Edexcel papers, read stem questions carefully. If asked to trace an algorithm, produce a neat trace table with columns for each variable and update row by row. If asked to write pseudocode, use clear indentation and consistent variable names; do not rely on Python-only syntax unless the question allows it.

    在 Edexcel 试卷中,要仔细阅读题干。如果要求跟踪算法,应画出清晰的跟踪表,为每个变量设置一列,并逐行更新。如果要求编写伪代码,应使用清晰的缩进和一致的变量名;除非题目允许,不要依赖 Python 独有的语法。

    Common pitfalls include off-by-one errors in loops, confusing assignment and comparison, forgetting to handle empty lists, and failing to return values from functions. Before finalising code, dry-run with small test data and check the problem statement against every output requirement.

    常见误区包括循环中的差一错误、混淆赋值与比较、忘记处理空列表以及函数没有返回值。在最终确定代码之前,应使用小规模测试数据进行人工推演,并将问题说明与每项输出要求逐一核对。


    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Constructs, Data Structures and Algorithms | 爱德思 A-Level 编程:程序结构、数据结构与算法

    📚 Edexcel A-Level Programming: Constructs, Data Structures and Algorithms | 爱德思 A-Level 编程:程序结构、数据结构与算法

    In Edexcel A-Level Computer Science, programming is not just about writing code; it is about designing solutions, choosing appropriate data structures, and analysing efficiency. This revision guide covers the core programming constructs, essential data structures, and algorithm design techniques that appear across Paper 1 and the programming project.

    在爱德思 A-Level 计算机科学中,编程不仅仅是写代码,更是设计解决方案、选择合适的数据结构以及分析算法效率。本复习指南涵盖 Paper 1 和编程项目中常见的核心程序结构、关键数据结构与算法设计方法。


    1. Programming Paradigms and Language Types | 编程范式与语言类型

    A programming paradigm is a fundamental style of writing programs. At A-Level, you mainly need to understand the procedural paradigm, where a program is broken into procedures or functions, and the object-oriented paradigm, where data and behaviour are grouped into classes and objects.

    编程范式是编写程序的基本风格。在 A-Level 阶段,你需要重点理解过程式范式(将程序拆分为过程或函数)和面向对象范式(将数据和行为组织为类与对象)。

    High-level languages such as Python, Java and C# are translated into machine code by compilers or interpreters. A compiler translates the whole source code before execution, while an interpreter translates and executes line by line.

    Python、Java 和 C# 等高级语言通过编译器或解释器翻译为机器码。编译器在执行前翻译整个源代码,而解释器逐行翻译并执行。

    Procedural code often uses top-down design and stepwise refinement. Object-oriented code uses encapsulation, inheritance and polymorphism to make large systems easier to maintain.

    过程式代码通常采用自顶向下设计和逐步求精。面向对象代码通过封装、继承和多态使大型系统更易于维护。


    2. Variables, Constants and Data Types | 变量、常量与数据类型

    A variable is a named storage location whose value can change during execution. A constant is a named value that cannot be changed after it is initialised. Using constants improves readability and reduces magic numbers.

    变量是命名的存储位置,其值在程序执行期间可以改变。常量是初始化后不可更改的命名值。使用常量可提高可读性并减少“魔法数字”。

    Common primitive data types include integer, real/float, Boolean, character and string. Some languages also provide date/time and enumeration types. Choosing the correct type affects memory use and the operations available.

    常见的基本数据类型包括整型、实型/浮点型、布尔型、字符型和字符串。一些语言还提供日期/时间和枚举类型。选择正确的类型会影响内存使用和可执行的操作。

    Type casting changes a value from one type to another, for example converting the string ’42’ to the integer 42. Implicit casting happens automatically when there is no data loss, while explicit casting must be written by the programmer.

    类型转换将值从一种类型转换为另一种类型,例如将字符串 ’42’ 转换为整数 42。隐式转换在没有数据丢失时自动发生,而显式转换必须由程序员编写。


    3. Sequence, Selection and Iteration | 顺序、选择与迭代

    Every program is built from three control constructs: sequence, selection and iteration. Sequence means statements execute one after another in order. Selection allows different paths with IF, ELSE IF, ELSE or CASE statements.

    所有程序都建立在三种控制结构之上:顺序、选择和迭代。顺序意味着语句按先后顺序执行。选择使用 IF、ELSE IF、ELSE 或 CASE 语句允许执行不同路径。

    Iteration repeats a block of code. Count-controlled loops such as FOR run a known number of times, while condition-controlled loops such as WHILE and REPEAT UNTIL run based on a Boolean condition.

    迭代重复执行一段代码。计数控制循环(如 FOR)运行已知次数,而条件控制循环(如 WHILE 和 REPEAT UNTIL)根据布尔条件运行。

    Pseudocode uses structured English to express logic without syntax concerns. The examples below show selection and iteration.

    伪代码使用结构化英语表达逻辑,无需关注语法。下面的示例展示选择和迭代。

    IF score ≥ 70 THEN
    grade ← ‘Distinction’
    ELSE IF score ≥ 40 THEN
    grade ← ‘Pass’
    ELSE
    grade ← ‘Fail’
    END IF

    FOR i ← 1 TO 10 DO
    OUTPUT i
    END FOR

    WHILE temperature < 20 DO
    heater ← TRUE
    END WHILE

    Notice that FOR is count-controlled; WHILE is condition-controlled. Both are essential for Edexcel problem-solving questions.

    请注意 FOR 是计数控制,WHILE 是条件控制。两者对爱德思问题求解题都必不可少。


    4. Arrays and Lists | 数组与列表

    A one-dimensional array stores elements of the same data type in contiguous memory locations. Each element is accessed by an index, usually starting at 0 or 1 depending on the language or pseudocode convention used by Edexcel.

    一维数组将相同数据类型的元素存储在连续的内存空间中。每个元素通过索引访问,索引通常从 0 或 1 开始,具体取决于语言或爱德思伪代码约定。

    A two-dimensional array can be thought of as a table with rows and columns. For example, matrix[2][0] refers to row index 2 and column index 0.

    二维数组可以看作由行和列组成的表格。例如,matrix[2][0] 表示行索引为 2、列索引为 0 的元素。

    Lists are more flexible than arrays because they can grow and shrink dynamically. Common list operations include append, insert, remove, search and sort.

    列表比数组更灵活,因为列表可以动态增长和缩小。常见的列表操作包括追加、插入、删除、搜索和排序。


    5. Stacks and Queues | 栈与队列

    A stack is a last-in-first-out (LIFO) structure. The main operations are push, which adds an item to the top, and pop, which removes the top item. Stacks support recursion, undo features and expression evaluation.

    栈是一种后进先出(LIFO)结构。主要操作是 push(将项添加到栈顶)和 pop(移除栈顶项)。栈支持递归、撤销功能和表达式求值。

    A queue is a first-in-first-out (FIFO) structure. Items are enqueued at the rear and dequeued from the front. Queues model waiting lines, print spooling and CPU scheduling.

    队列是一种先进

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Concepts and Exam Skills | 爱德思 A-Level 编程:核心概念与应试技巧

    📚 Edexcel A-Level Programming: Core Concepts and Exam Skills | 爱德思 A-Level 编程:核心概念与应试技巧

    Programming is at the heart of the Edexcel A-Level Computer Science specification. This revision guide brings together the essential programming constructs, algorithms and problem-solving techniques you need to score confidently on Paper 1 and the practical programming project. We focus on exam-style thinking: reading code, writing pseudocode, tracing variables and comparing algorithm efficiency.

    编程是爱德思 A-Level 计算机科学考试的核心。本复习指南整合了关键编程结构、算法和问题求解方法,帮助你在 Paper 1 和编程课程项目中自信得分。我们重点训练考试型思维:读代码、写伪代码、追踪变量和比较算法效率。


    1. Programming Paradigms | 编程范式

    Edexcel distinguishes three main paradigms: procedural, object-oriented and functional. Procedural code organises logic into procedures or functions that operate on shared data. Object-oriented code encapsulates data and behaviour inside classes, while functional code builds programs from pure functions and avoids mutable state.

    爱德思区分三种主要范式:过程式、面向对象和函数式。过程式代码将逻辑组织为操作共享数据的过程或函数。面向对象代码将数据和行为封装在类中,而函数式代码由纯函数构建程序,并避免可变状态。

    In the exam you may be asked to identify a paradigm from a short code sample. Look for class definitions, inheritance and dot notation for OOP; top-level procedures and global variables for procedural; and first-class functions, map/filter or recursion for functional.

    考试中可能要求你从短代码片段识别范式。面向对象看类定义、继承和点号访问;过程式看顶层过程和全局变量;函数式看高阶函数、map/filter 或递归。


    2. Data Types and Structures | 数据类型与结构

    Core data types include integer, real/float, Boolean, character and string. Composite types such as arrays, records, lists and dictionaries let you organise related values. Choosing the right structure affects both clarity and runtime performance.

    核心数据类型包括整数、实数/浮点数、布尔、字符和字符串。数组、记录、列表和字典等复合类型用于组织相关值。选择正确的结构既影响代码清晰度也影响运行性能。

    For example, a record groups fields of mixed types, while a 2D array is ideal for a grid or matrix. Make sure you can declare and initialise these structures in pseudocode and in your chosen project language.

    例如,记录将不同类型的字段分组,二维数组适合网格或矩阵。确保你能在伪代码和所选项目语言中声明并初始化这些结构。


    3. Control Structures | 控制结构

    All algorithms are built from sequence, selection and iteration. Sequence executes statements in order. Selection uses IF/ELSE or CASE to branch. Iteration uses FOR, WHILE or REPEAT loops to repeat blocks until a condition changes.

    所有算法都由顺序、选择和迭代构成。顺序按次序执行语句。选择用 IF/ELSE 或 CASE 分支。迭代用 FOR、WHILE 或 REPEAT 循环重复代码块,直到条件改变。

    A common exam skill is converting a WHILE loop to an equivalent FOR loop and vice versa. State the loop invariant clearly: which condition stays true before and after each iteration.

    常见的考试技能是在 WHILE 循环和 FOR 循环之间等价转换。清晰写出循环不变量:每次迭代前后保持为真的条件是什么。


    4. Functions and Procedures | 函数与过程

    A function returns a value; a procedure performs an action without returning one. Parameters can be passed by value or by reference. Passing by value copies the data, so the original variable is safe. Passing by reference allows the subroutine to modify the caller’s variable.

    函数返回一个值;过程执行操作但不返回值。参数可以按值或按引用传递。按值传递复制数据,因此原变量安全。按引用传递允许子程序修改调用者的变量。

    Use local variables inside subroutines to reduce side effects. Edexcel pseudocode often uses SUBROUTINE … ENDSUBROUTINE, with RETURN for functions. Always trace calls with a call stack diagram when recursion is involved.

    在子程序内部使用局部变量以减少副作用。爱德思伪代码通常使用 SUBROUTINE … ENDSUBROUTINE,函数用 RETURN。涉及递归时,始终用调用栈图追踪调用过程。


    5. Object-Oriented Programming | 面向对象编程

    Classes define attributes and methods. Encapsulation hides internal state and exposes a public interface. Inheritance allows a subclass to reuse and extend a parent class. Polymorphism lets the same method name behave differently in different classes.

    类定义属性和方法。封装隐藏内部状态并公开接口。继承允许子类重用和扩展父类。多态允许同名方法在不同类中表现不同。

    In Edexcel questions, be ready to design a class diagram, identify a constructor, or explain why encapsulation improves maintainability. Use UML-style notation with private (-) and public (+) members.

    在爱德思考题中,要准备好设计类图、识别构造函数或解释封装为何能提高可维护性。使用 UML 风格标记私有 (-) 和公有 (+) 成员。


    6. File Handling and Exceptions | 文件处理与异常

    Programs often read from and write to text or binary files. The standard pattern is open, process, close. Use TRY … EXCEPT or ON ERROR blocks to handle missing files, invalid data and permission errors gracefully.

    程序经常读写文本或二进制文件。标准模式是打开、处理、关闭。使用 TRY … EXCEPT 或 ON ERROR 块优雅地处理文件缺失、无效数据和权限错误。

    Make sure to close files in a FINALLY block or use a context manager. When writing pseudocode, state the file mode: READ, WRITE or APPEND. For structured data, consider CSV or JSON lines for easy parsing.

    确保在 FINALLY 块中关闭文件或使用上下文管理器。写伪代码时,注明文件模式:READ、WRITE 或 APPEND。对于结构化数据,可考虑 CSV 或 JSON 行以便解析。


    7. Searching Algorithms | 查找算法

    Linear search checks every element until the target is found or the list ends. It works on unsorted data and has worst-case time complexity O(n). Binary search repeatedly halves a sorted list, achieving O(log n) time.

    线性查找逐个检查元素,直到找到目标或列表结束。它适用于未排序数据,最坏时间复杂度为 O(n)。二分查找在有序列表上反复折半,时间复杂度为 O(log n)。

    You must be able to write binary search pseudocode with low, high and mid pointers. A common mistake is using mid = (low + high) / 2 when the list is not sorted; binary search requires a sorted input.

    你必须能写出带 low、high、mid 指针的二分查找伪代码。常见错误是在列表未排序时使用 mid = (low + high) / 2;二分查找要求输入已排序。

    Algorithm Precondition Worst-case time
    Linear search None O(n)
    Binary search Sorted list O(log n)

    8. Sorting Algorithms | 排序算法

    Bubble sort compares adjacent pairs and swaps them if needed, making multiple passes. It is simple but slow at O(n²). Insertion sort builds a sorted portion by inserting each new element into place, also O(n²) but efficient for nearly sorted data.

    冒泡排序比较相邻元素并在需要时交换,进行多轮。它实现简单但时间复杂度为 O(n²)。插入排序通过将每个新元素插入有序区来构建有序部分,也是 O(n²),但接近有序时效率较高。

    Merge sort and quicksort are divide-and-conquer algorithms that improve average performance to O(n log n). Merge sort guarantees O(n log n) but needs extra memory; quicksort is in-place but has O(n²) worst case if pivot choice is poor.

    归并排序和快速排序是分治算法,平均性能提升到 O(n log n)。归并排序保证 O(n log n) 但需要额外内存;快速排序原地排序,但枢轴选择不佳时最坏为 O(n²)。

    Algorithm Average time Worst time Space
    Bubble sort O(n²) O(n²) O(1)
    Insertion sort O(n²) O(n²) O(1)
    Merge sort O(n log n) 更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Techniques and Exam Success | Edexcel A-Level 编程:核心技巧与考试决胜

    📚 Edexcel A-Level Programming: Core Techniques and Exam Success | Edexcel A-Level 编程:核心技巧与考试决胜

    Programming is not just about writing code; it is a discipline of precise thinking, systematic design and rigorous evaluation. In the Edexcel A-Level Computer Science qualification, programming underpins many areas of assessment, including problem solving, algorithms, data structures and coursework projects.

    编程不只是写代码,更是一种精确思维、系统设计和严格评估的学科。在 Edexcel A-Level 计算机科学考试中,编程是许多考核领域的核心,包括问题解决、算法、数据结构以及课程项目。

    This revision guide covers the core programming concepts you need for Edexcel, with exam strategies, pseudocode examples and common pitfalls explained in a bilingual format to help both English and Chinese learners.

    本复习指南涵盖 Edexcel 所需的核心编程概念,并以双语形式解释考试策略、伪代码示例和常见失分点,帮助中英文学习者。


    1. The Edexcel Programming Syllabus at a Glance | Edexcel 编程考纲概览

    In Edexcel A-Level Computer Science, programming is assessed through written examinations and, depending on your centre, a programming project. The specification rewards candidates who can express algorithms clearly, match code to its purpose, and evaluate a program’s efficiency and correctness.

    在 Edexcel A-Level 计算机科学中,编程通过笔试以及课程项目进行考核。考纲奖励那些能够清晰地表达算法、将代码与其功能对应起来,并评估程序效率和正确性的考生。

    The most common question types include completing trace tables, identifying errors, writing pseudocode or program code, and discussing the advantages of different programming constructs. Therefore, your revision should not only cover syntax but also the underlying logic.

    最常见的题型包括完成跟踪表、识别错误、编写伪代码或程序代码,以及讨论不同编程结构的优缺点。因此,复习不仅要覆盖语法,还要掌握底层逻辑。

    Assessment focus What you need to show
    Algorithms Clear steps, correct logic, appropriate constructs
    Programming constructs Sequence, selection, iteration and subroutines
    Data structures Arrays, lists, records and file handling
    Testing and debugging Trace tables, error types and IDE tools

    Understanding these assessment focuses allows you to organise revision around the exact skills Edexcel examiners look for, rather than trying to memorise code without purpose.

    理解这些考核重点可以帮助你围绕 Edexcel 考官所看重的能力来组织复习,而不是漫无目的地死记代码。


    2. Computational Thinking Before Coding | 编码之前的计算思维

    Before writing any code, you should decompose the problem, abstract away irrelevant details, and identify patterns or repeated operations. This is the computational thinking process that Edexcel examiners expect to see in longer written responses.

    在开始编写代码之前,你应当分解问题、抽象掉无关细节,并识别模式或重复操作。这就是 Edexcel 考官在较长的书面回答中希望看到的计算思维过程。

    For example, when asked to calculate the average of a list, you first decompose the task into input, summation, division and output. You then abstract by ignoring where the numbers come from, and you notice the pattern of repeated addition.

    例如,当要求计算一组数的平均值时,你首先将任务分解为输入、求和、除法与输出。然后通过忽略数字的来源进行抽象,并注意到重复相加的模式。

    In the exam, a few sentences of planning can help you avoid unstructured answers. Write down the inputs, the main process and the outputs before you begin your pseudocode or explanation.

    在考试中,几句规划性的文字可以帮助你避免结构混乱的回答。在开始编写伪代码或解释之前,先把输入、主要过程和输出写下来。


    3. Data Types, Variables and Constants | 数据类型、变量与常量

    Variables are named storage locations whose values can change during execution, whereas constants are fixed values that cannot be modified after declaration. Edexcel questions often ask you to choose the most appropriate data type for a given value.

    变量是命名的存储位置,其值在执行过程中可以改变;常量则是在声明后不能修改的固定值。Edexcel 试题经常要求你为给定值选择最合适的数据类型。

    Data type Example values Typical use
    INTEGER 3, -15, 208 Counting, indexing
    REAL / FLOAT 更多咨询请联系16621398022(同微信)

  • Core Programming Constructs and Algorithms for Edexcel A-Level | Edexcel A-Level 核心编程构造与算法

    📚 Core Programming Constructs and Algorithms for Edexcel A-Level | Edexcel A-Level 核心编程构造与算法

    This article covers the essential programming constructs, data structures and algorithms required for the Edexcel A-Level Computer Science specification. You will learn how to trace code, apply pseudocode ideas and translate them into Python, with clear examples and exam-focused explanations.

    本文介绍 Edexcel A-Level 计算机科学考试中必备的核心编程构造、数据结构和算法。你将学会如何跟踪代码、运用伪代码思想并将其转换为 Python,配合清晰的示例和紧扣考点的解释。


    1. Data Types and Variables | 数据类型与变量

    In Edexcel A-Level programming questions, you must distinguish between primitive data types and compound data types. The common primitive types are integer, real/float, Boolean and character. A variable is a named memory location whose value can change during execution; a constant is fixed at compile time. Strong typing requires every variable to be declared with a type, while Python uses dynamic typing but you still need to reason about types when tracing code.

    在 Edexcel A-Level 编程题中,你必须区分基本数据类型和复合数据类型。常见的基本类型有整型、实型/浮点型、布尔型和字符型。变量是命名的内存位置,其值在执行期间可以改变;常量在编译时固定。强类型要求声明变量的类型,而 Python 使用动态类型,但你在跟踪代码时仍需推断类型。

    When tracing code, watch for implicit type conversion: in Python, 3/2 gives 1.5, while 3//2 gives 1. Integer division in pseudocode DIV also gives the whole-number quotient. Variables should have meaningful names and follow the language’s naming rules, such as no spaces and not starting with a digit.

    跟踪代码时,注意隐式类型转换:在 Python 中 3/2 得到 1.5,而 3//2 得到 1。伪代码中的整数除法 DIV 也给出整数商。变量应使用有意义的名称,并遵循语言命名规则,例如不能包含空格,不能以数字开头。


    2. Operators and Expressions | 运算符与表达式

    Operators build expressions. Arithmetic operators +,

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Techniques from Data Types to Recursion | Edexcel A-Level 编程核心技法:从数据类型到递归

    📚 Edexcel A-Level Programming: Core Techniques from Data Types to Recursion | Edexcel A-Level 编程核心技法:从数据类型到递归

    This revision article covers the essential programming skills tested in Edexcel A-Level Computing. You will review data types, control structures, subroutines, parameter passing, arrays, strings, file handling, recursion, exception handling, and algorithm efficiency. Each section pairs a clear English explanation with a Chinese translation to support bilingual learners. The focus is on exam-style understanding, trace tables, and correct pseudocode conventions.

    本篇复习文章涵盖 Edexcel A-Level 计算机编程的核心技能。你将回顾数据类型、控制结构、子程序、参数传递、数组、字符串、文件处理、递归、异常处理以及算法效率。每个小节都提供清晰的英文解释并配以中文翻译,方便双语学习者。重点在于考试风格的理解、跟踪表以及正确的伪代码规范。

    1. Data Types and Type Casting | 数据类型与类型转换

    In Edexcel A-Level programming, you must be confident with primitive data types: integer, real or float, boolean, character, and string. Each type has a specific memory footprint and allowed range. Choosing the wrong type can cause overflow when values exceed the maximum limit or loss of precision when real numbers are stored incorrectly.

    在 Edexcel A-Level 编程中,你必须熟练掌握基本数据类型:整数、实数或浮点数、布尔值、字符和字符串。每种类型都有特定的内存占用量和允许范围。如果选错类型,当数值超过最大限制时会发生溢出,或者实数被错误存储时会造成精度丢失。

    Type casting converts data from one type to another, such as int(“42”) or str(3.14). However, casting is only safe when the original data can be interpreted in the target type. For example, int(“3.14”) causes a runtime error because the string “3.14” is not a valid integer literal. Exam questions often test whether you validate input before casting.

    类型转换将数据从一种类型转换为另一种类型,例如 int(“42”) 或 str(3.14)。然而,只有当原始数据能够被解释为目标类型时,类型转换才是安全的。例如,int(“3.14”) 会导致运行时错误,因为字符串 “3.14” 不是有效的整数字面量。考题经常考查你是否在类型转换之前验证了输入。

    A common pitfall is mixing integer and float in division. In many languages, 5 / 2 returns 2.5 if real division is used, while 5 DIV 2 returns 2 for integer division. Be clear about which operator your pseudocode is using.

    一个常见的误区是在除法中混用整数和浮点数。在许多语言中,如果使用实数除法,5 / 2 返回 2.5;而 5 DIV 2 返回整数除法的结果 2。要清楚你的伪代码使用的是哪种运算符。


    2. Operators and Expressions | 运算符与表达式

    Arithmetic operators include addition, subtraction, multiplication, division, integer DIV, and modulus MOD. DIV gives the quotient without the remainder, while MOD gives the remainder only. For example, 17 DIV 5 = 3 and 17 MOD 5 = 2. These are extremely useful for problems involving cycles, divisibility, or grouping.

    算术运算符包括加、减、乘、除、整数 DIV 和取模 MOD。DIV 给出商但不含余数,MOD 只给出余数。例如,17 DIV 5 = 3,17 MOD 5 = 2。它们在处理循环、整除或分组问题时非常有用。

    Comparison operators such as <, >, <=, >=, ==, and != produce Boolean results. Logical operators AND, OR, and NOT combine or invert Boolean expressions. Operator precedence is critical: NOT is evaluated before AND, and AND before OR. Parentheses should be used to make the order of evaluation explicit and to avoid logic errors.

    比较运算符如 <、>、<=、>=、== 和 != 产生布尔结果。逻辑运算符 AND、OR 和 NOT 用于组合或取反布尔表达式。运算符优先级非常重要:NOT 先于 AND 求值,AND 先于 OR。应使用圆括号明确求值顺序,避免逻辑错误。

    In Edexcel pseudocode, assignments often use the arrow symbol ←, while comparisons use = or == depending on the style. Always distinguish between assignment and equality testing because exam questions may ask you to find a bug caused by confusing the two.

    在 Edexcel 伪代码中,赋值通常使用箭头符号 ←,而比较则根据风格使用 = 或 ==。务必区分赋值和相等性测试,因为考题可能会要求你找出由于混淆两者而导致的错误。


    3. Selection: if, elif, else | 选择结构:if、elif、else

    The if-elif-else structure allows a program to branch based on the value of a Boolean condition. A basic if statement executes a block only when the condition is true. An else clause handles the false case, and elif lets you test multiple conditions in sequence without excessive nesting.

    if-elif-else 结构允许程序根据布尔条件的值进行分支。基本的 if 语句仅在条件为真时执行某个代码块。else 子句处理条件为假的情况,elif 则允许你按顺序测试多个条件,避免过多嵌套。

    Always place the most specific or restrictive condition first when using elif. For example, if checking score >= 90, score >= 70, and score >= 50, the first condition should catch the highest range. If the order is reversed, lower ranges will incorrectly absorb higher scores.

    使用 elif 时,始终将最具体或最严格的条件放在最前面。例如,检查 score >= 90、score >= 70 和 score >= 50 时,第一个条件应该捕获最高分数段。如果顺序颠倒,较低分数段会错误地包含较高分数。

    Boolean variables can simplify selection. Instead of writing if flag == True, write if flag. This reduces redundancy and makes the condition easier to read. Exam questions may present nested selection and ask you to draw a decision tree or complete a trace table.

    布尔变量可以简化选择结构。不要写 if flag == True,而应写 if flag。这样可以减少冗余,使条件更易读。考题可能给出嵌套选择结构,要求你画出决策树或填写跟踪表。


    4. Iteration: Count-Controlled and Condition-Controlled Loops | 迭代:计数控制与条件控制循环

    Count-controlled loops repeat a fixed number of times. In Edexcel pseudocode, this is typically written as FOR i ← 1 TO n … ENDFOR. The loop variable takes each value in the specified range. This is ideal when you know in advance how many iterations are needed.

    计数控制循环重复固定次数。在 Edexcel 伪代码中,通常写作 FOR i ← 1 TO n … ENDFOR。循环变量依次取指定范围内的每个值。当你事先知道需要多少次迭代时,这是理想的选择。

    Condition-controlled loops repeat while a condition is true or until a condition becomes true. The WHILE loop checks the condition before each iteration, so it may execute zero times. The REPEAT…UNTIL loop checks after each iteration, so it always executes at least once.

    条件控制循环在条件为真时重复,或重复直到条件变为真。WHILE 循环在每次迭代之前检查条件,因此可能执行零次。REPEAT…UNTIL 循环在每次迭代之后检查条件,因此总是至少执行一次。

    A trace table is essential for recording variable values during each iteration. When you analyse a loop, update the loop counter, condition, and any accumulator step by step. A common exam error is failing to write down the value of the loop condition at the end of each pass, leading to an incorrect final output.

    跟踪表对于记录每次迭代中的变量值至关重要。分析循环时,要逐步更新循环计数器、条件和所有累加器。考试中常见的错误是未能写出每轮结束时循环条件的值,从而得出错误的最终输出。


    5. Subroutines: Procedures and Functions | 子程序:过程与函数

    Subroutines break a complex problem into smaller, reusable blocks. A procedure performs a task but does not return a value. A function performs a task and returns exactly one value. In Python, a procedure is simply a function that returns None implicitly.

    子程序将复杂问题分解为更小的、可复用的代码块。过程执行任务但不返回值。函数执行任务并返回且仅返回一个值。在 Python 中,过程只是隐式返回 None 的函数。

    Using parameters and local variables improves modularity and avoids unintended side effects. Local variables are created when the subroutine is called and destroyed when it finishes. Global variables should be used sparingly because they make debugging and reasoning about programs more difficult.

    使用参数和局部变量可以提高模块化程度,避免意外的副作用。局部变量在子程序被调用时创建,在子程序结束时销毁。全局变量应尽量少用,因为它们会使程序的调试和推理更加困难。

    Edexcel exam questions often provide pseudocode for a subroutine and ask for the output after a particular call. Practise dry running subroutines by drawing a call stack or by writing down the values passed back and forth. Pay close attention to whether a variable is being updated or replaced.

    Edexcel 考题经常给出子程序的伪代码,并要求回答特定调用后的输出。练习通过绘制调用栈或写下来回传递的值来手工执行子程序。要特别注意变量是被更新还是被替换。


    6. Parameter Passing: By Value and By Reference | 参数传递:按值与按引用

    By value passes a copy of the argument to the subroutine. Any changes made to the parameter inside the subroutine do not affect the original variable outside. By reference passes the memory address, so the subroutine can modify the original data directly.

    按值传递将参数的副本传递给子程序。子程序内部对参数所做的任何更改都不会影响外部的原始变量。按引用传递传递的是内存地址,因此子程序可以直接修改原始数据。

    In Python, integers, floats, strings, and booleans are immutable, so they behave like by-value arguments. Lists and dictionaries, however, are mutable and behave like by-reference arguments. This distinction is important when predicting the output of a subroutine that modifies an array.

    在 Python 中,整数、浮点数、字符串和布尔值是不可变的,因此它们的行为类似于按值传递的参数。然而,列表和字典是可变的,行为类似于按引用传递的参数。在预测修改数组的子程序的输出时,这一区别非常重要。

    Edexcel pseudocode may explicitly state whether parameters are passed by value or by reference, or you may need to infer it from the problem context. If a subroutine needs to return more than one result, by-reference parameters can be used, but a cleaner approach is often to return a record or tuple.

    Edexcel 伪代码可能会明确说明参数是按值还是按引用传递,也可能需要你根据问题背景进行推断。如果子程序需要返回多个结果,可以使用按引用传递的参数,但更清晰的做法往往是返回一条记录或元组。


    7. Arrays, Lists and 2D Structures | 数组、列表与二维结构

    Arrays store multiple values under one identifier and use an index to access each element. The first index may be 0 or 1 depending on the language or pseudocode convention. Always state your indexing assumption when writing Edexcel answers.

    数组在一个标识符下存储多个值,并使用索引访问每个元素。第一个索引可能是 0 或 1,具体取决于语言或伪代码规范。在编写 Edexcel 答案时,务必说明你的索引假设。

    A 2D array is an array of arrays, often visualised as a grid with rows and columns. It is accessed using two indices, such as grid[row, column]. Common operations include traversing all elements, summing rows, and searching for a maximum or minimum value.

    二维数组是数组的数组,通常可视化为带有行和列的网格。它使用两个索引进行访问,例如 grid[row, column]。常见的操作包括遍历所有元素、对各行求和以及查找最大值或最小值。

    You should be able to write pseudocode for insertion, deletion, linear search, and finding the average. Remember that updating an array inside a subroutine may affect the original array if the language uses by-reference semantics for mutable objects.

    你应该能够编写插入、删除、线性搜索和求平均值的伪代码。请记住,如果语言对可变对象使用按引用语义,在子程序内部更新数组可能会影响原始数组。


    8. String Handling and File I/O | 字符串处理与文件输入输出

    String operations frequently tested include length, substring, concatenation, and character access. For example, in many languages string[0] returns the first character, and length(string) returns the number of characters. Concatenation uses + or & depending on the language.

    经常考查的字符串操作包括长度、子串、连接和字符访问。例如,在许多语言中,string[0] 返回第一个字符,length(string) 返回字符数量。连接操作根据语言使用 + 或 &。

    File handling follows a standard sequence: open, read or write, then close. You should always close a file to release resources and ensure data is flushed to disk. Exam questions may ask you to read a text file line by line and count words

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Edexcel A-Level Programming: Core Constructs and Algorithms | Edexcel A-Level 编程:核心结构与算法

    📚 Edexcel A-Level Programming: Core Constructs and Algorithms | Edexcel A-Level 编程:核心结构与算法

    This revision guide covers the essential programming knowledge required for the Edexcel A-Level Computer Science specification. It focuses on core programming constructs, data structures, subroutines, recursion, file handling, searching and sorting algorithms, complexity analysis, and exam techniques.

    本复习指南涵盖 Edexcel A-Level 计算机科学考试大纲所要求的核心编程知识。重点包括编程基本结构、数据结构、子程序、递归、文件处理、搜索与排序算法、复杂度分析以及考试技巧。


    1. Programming Paradigms and Structure | 编程范式与程序结构

    Programming paradigms are fundamental styles of programming. The two most relevant to Edexcel A-Level are procedural programming and object-oriented programming. Procedural programming organises code into procedures or functions that operate on data, while object-oriented programming bundles data and methods into objects.

    编程范式是编程的基本风格。与 Edexcel A-Level 最相关的两种范式是面向过程编程和面向对象编程。面向过程编程将代码组织为操作数据的过程或函数,而面向对象编程将数据和方法封装在对象中。

    A well-structured program is modular, with each module performing a single clear task. This improves readability, maintainability, and testability. You should be able to write pseudocode that follows a logical top-down design.

    结构良好的程序是模块化的,每个模块执行单一明确的任务。这提高了可读性、可维护性和可测试性。你应该能够编写遵循逻辑自顶向下设计的伪代码。


    2. Data Types and Variables | 数据类型与变量

    Data types define what kind of value a variable can hold. Common primitive types include integer, real, Boolean, character, and string. Choosing the correct data type affects memory usage and the operations that can be performed.

    数据类型定义变量可以保存何种值。常见的基本类型包括整数、实数、布尔型、字符和字符串。选择正确的数据类型会影响内存使用以及可执行的操作。

    A variable is a named memory location whose value can change during execution. A constant is similar but its value cannot be modified after initialisation. You must understand variable scope, including local and global variables.

    变量是一个命名的内存位置,其值在执行期间可以改变。常量类似,但初始化后其值不可修改。你必须理解变量的作用域,包括局部变量和全局变量。


    3. Sequence, Selection, and Iteration | 顺序、选择与迭代

    All procedural programs are built from three basic control structures: sequence, selection, and iteration. Sequence means statements are executed in the order written. Selection allows branching based on conditions, using IF, ELSE IF, ELSE, and CASE statements.

    所有面向过程的程序都由三种基本控制结构构建:顺序、选择和迭代。顺序意味着语句按编写的顺序执行。选择允许根据条件进行分支,使用 IF、ELSE IF、ELSE 和 CASE 语句。

    Iteration repeats a block of code. Definite iteration, such as a FOR loop, runs a known number of times. Indefinite iteration, such as a WHILE or REPEAT UNTIL loop, continues until a condition is met. Infinite loops occur when the termination condition is never satisfied.

    迭代重复执行代码块。确定迭代(如 FOR 循环)运行已知次数。不确定迭代(如 WHILE 或 REPEAT UNTIL 循环)持续到满足条件为止。当终止条件永远不满足时,就会发生无限循环。


    4. Arrays and Lists | 数组与列表

    Arrays and lists store multiple values under one identifier. A one-dimensional array is a fixed-size indexed collection, whereas a list is often dynamic and supports insertion and deletion. A two-dimensional array can model a table or grid.

    数组和列表在一个标识符下存储多个值。一维数组是固定大小的索引集合,而列表通常是动态的,支持插入和删除。二维数组可以模拟表格或网格。

    When manipulating arrays, you must be careful with index bounds. Many languages use zero-based indexing, so the first element is at index 0. Accessing an out-of-range index causes a runtime error.

    操作数组时,必须注意索引边界。许多语言使用从零开始的索引,因此第一个元素位于索引 0。访问越界索引会导致运行时错误。


    5. Subroutines: Procedures and Functions | 子程序:过程与函数

    A subroutine is a named block of code that can be called from elsewhere in the program. Procedures perform a task but do not return a value. Functions perform a task and return a value to the caller.

    子程序是一段命名代码块,可以从程序的其他位置调用。过程执行任务但不返回值。函数执行任务并向调用者返回一个值。

    Parameters allow data to be passed into subroutines. Passing by value copies the argument, while passing by reference passes the memory address, allowing changes to affect the original variable. Return values are produced using a RETURN statement.

    参数允许将数据传入子程序。按值传递会复制实参,而按引用传递传递内存地址,允许更改影响原始变量。返回值使用 RETURN 语句产生。


    6. Recursion | 递归

    Recursion is a technique where a subroutine calls itself to solve a smaller instance of the same problem. Every recursive algorithm must have a base case that stops the recursion and a recursive case that reduces the problem size.

    递归是一种子程序调用自身来解决同一问题的较小实例的技术。每个递归算法必须有一个停止递归的基准情况,以及一个减小问题规模的递归情况。

    A classic example is the factorial function: factorial(n) = n × factorial(n – 1) with factorial(1) = 1 as the base case. Recursion can be elegant but may use more memory due to the call stack.

    一个经典示例是阶乘函数:factorial(n) = n × factorial(n – 1),基准情况为 factorial(1) = 1。递归可能很优雅,但由于调用栈可能会使用更多内存。


    7. File Handling and Exception Management | 文件处理与异常管理

    Programs often need to read from and write to files. Typical operations include opening a file in read, write, or append mode, reading lines or records, writing data, and closing the file. Always close files to prevent data loss.

    程序通常需要读写文件。典型操作包括以读、写或追加模式打开文件,读取行或记录,写入数据以及关闭文件。始终关闭文件以防止数据丢失。

    Exceptions are runtime errors that can be handled using TRY, EXCEPT, and FINALLY blocks. Exception handling makes programs more robust by preventing crashes when unexpected input or file errors occur.

    异常是可以使用 TRY、EXCEPT 和 FINALLY 块处理的运行时错误。异常处理通过在发生意外输入或文件错误时防止崩溃,使程序更加健壮。


    8. Searching Algorithms | 搜索算法

    Linear search checks each element in order until the target is found or the end is reached. It works on unsorted data and has a worst-case time complexity of O(n).

    线性搜索按顺序检查每个元素,直到找到目标或到达末尾。它适用于未排序的数据,最坏情况时间复杂度为 O(n)。

    Binary search repeatedly divides a sorted list in half, comparing the middle element with the target. If the target is smaller, search the left half; if larger, search the right half. It has a time complexity of O(log n) but requires sorted data.

    二分搜索反复将有序列表分成两半,将中间元素与目标比较。如果目标较小,搜索左半部分;如果较大,搜索右半部分。其时间复杂度为 O(log n),但要求数据有序。


    9. Sorting Algorithms | 排序算法

    Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The largest unsorted element ‘bubbles’ to the end each pass. It has average and worst-case complexity O(n²).

    冒泡排序反复遍历列表,比较相邻元素,如果顺序错误则交换它们。最大的未排序元素每次遍历都会“冒泡”到末尾。其平均和最坏情况复杂度为 O(n²)。

    Merge sort uses a divide-and-conquer approach: split the list into halves recursively, sort each half, then merge the sorted halves. It has a guaranteed time complexity of O(n log n) but uses additional memory.

    归并排序使用分治方法:递归地将列表分成两半,对每一半进行排序,然后合并已排序的两半。它的时间复杂度保证为 O(n log n),但使用额外内存。


    10. Algorithm Complexity and Big O Notation | 算法复杂度与大 O 表示法

    Big O notation describes the upper bound of an algorithm’s time or space requirements as the input size n grows. Common complexities include O(1), O(log n), O(n), O(n log n), O(n²), and O(2ⁿ).

    大 O 表示法描述随着输入规模 n 增长,算法时间或空间需求的上界。常见复杂度包括 O(1)、O(log n)、O(n)、O(n log n)、O(n²) 和 O(2ⁿ)。

    Constant time O(1) means runtime does not depend on input size. Linear time O(n) means runtime grows proportionally with input size. Quadratic time O(n²) means doubling input quadruples runtime, which becomes impractical for large data sets.

    常数时间 O(1) 意味着运行时间不依赖于输入规模。线性时间 O(n) 意味着运行时间与输入规模成正比增长。二次时间 O(n²) 意味着输入翻倍会使运行时间变为四倍,这对于大数据集变得不切实际。


    11. Debugging and Testing | 调试与测试

    Debugging is the process of finding and fixing errors in code. Syntax errors occur when the code violates language rules. Logic errors occur when the code runs but produces incorrect results. Runtime errors occur during execution, such as division by zero.

    调试是查找并修复代码错误的过程。语法错误在代码违反语言规则时发生。逻辑错误在代码运行但产生错误结果时发生。运行时错误在执行期间发生,例如除以零。

    Testing strategies include dry run, trace tables, unit testing, and integration testing. A trace table records variable values at each step, helping you verify that loops and conditions behave as intended.

    测试策略包括干运行、跟踪表、单元测试和集成测试。跟踪表记录每一步的变量值,帮助你验证循环和条件按预期运行。


    12. Exam Techniques and Pseudocode | 考试技巧与伪代码

    In the Edexcel A-Level exam, you may be asked to read, trace, or write pseudocode. Pseudocode should be clear, unambiguous, and use consistent indentation. It does not need to follow the syntax of a specific programming language.

    在 Edexcel A-Level 考试中,你可能会被要求阅读、跟踪或编写伪代码。伪代码应当清晰、无歧义,并使用一致的缩进。它不需要遵循特定编程语言的语法。

    When designing a solution, break the problem into smaller parts, define inputs and outputs, and identify the control structures needed. Show your working in trace tables and justify your choice of algorithm based on efficiency and data conditions.

    设计解决方案时,将问题分解为更小的部分,定义输入和输出,并确定所需的控制结构。在跟踪表中展示工作过程,并根据效率和数据条件证明算法选择的合理性。

    Published by TutorHao | Programming Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming in Python for Edexcel A-Level | Edexcel A-Level Python 面向对象编程详解

    📚 Object-Oriented Programming in Python for Edexcel A-Level | Edexcel A-Level Python 面向对象编程详解

    Object-oriented programming (OOP) is one of the most important paradigms assessed in the Edexcel A-Level Computer Science specification. Mastering OOP concepts in Python not only helps you write modular and reusable code but also prepares you for questions on class design, inheritance, and relationships. This article provides a comprehensive revision guide, covering every key OOP topic you need for the exam, with clear examples and exam-focused insights.

    面向对象编程(OOP)是 Edexcel A-Level 计算机科学考试中最重要的编程范式之一。掌握 Python 中的 OOP 概念不仅能帮助你编写模块化、可复用的代码,还能为应对类设计、继承和关系类考题做好准备。本文是一份全面的复习指南,涵盖考试所需的所有关键 OOP 主题,并配有清晰的示例和考试重点解析。

    1. What is Object-Oriented Programming? | 什么是面向对象编程?

    OOP is a programming paradigm that organizes code around ‘objects’ rather than functions and logic. Objects contain data, in the form of attributes, and behaviour, in the form of methods. The four main pillars of OOP are encapsulation, inheritance, polymorphism, and abstraction. In Edexcel A-Level, you need to understand how these principles are implemented in Python and how they lead to better software design.

    面向对象编程是一种围绕“对象”而非函数和逻辑来组织代码的编程范式。对象包含数据(以属性的形式)和行为(以方法的形式)。OOP 的四大支柱是封装、继承、多态和抽象。在 Edexcel A-Level 考试中,你需要理解这些原则如何在 Python 中实现,以及它们如何带来更好的软件设计。


    2. Classes and Objects | 类与对象

    A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from it will have. You define a class in Python using the class keyword. For example, class Dog: followed by an indented block. An object is an instance of a class. To create an object, you call the class as if it were a function: my_dog = Dog().

    类是创建对象的蓝图。它定义了一组从该类创建的对象将具有的属性和方法。在 Python 中,使用 class 关键字定义类。例如,class Dog: 后跟缩进块。对象是类的一个实例。要创建对象,你可以像调用函数一样调用类:my_dog = Dog()

    Each object has its own copy of the instance attributes, and multiple objects can be created from the same class. The self parameter refers to the current instance and is used to access attributes and methods within the class.

    每个对象都有自己的实例属性副本,并且可以从同一个类创建多个对象。self 参数指向当前实例,并用于在类内部访问属性和方法。


    3. Attributes and Methods | 属性与方法

    Attributes are variables that belong to a class (class attributes) or to an instance (instance attributes). Instance attributes are typically defined inside the __init__ method using self.attribute_name = value. Class attributes are defined directly inside the class body and are shared by all instances.

    属性是属于类(类属性)或实例(实例属性)的变量。实例属性通常在使用 self.attribute_name = value__init__ 方法中定义。类属性直接定义在类体内,并由所有实例共享。

    Methods are functions defined inside a class. They always take self as the first parameter (unless they are static or class methods). Methods operate on the instance data and can modify the object’s state. You call a method on an object: my_dog.bark().

    方法是定义在类内部的函数。它们始终将 self 作为第一个参数(除非是静态方法或类方法)。方法操作实例数据,并可以修改对象的状态。你可以在对象上调用方法:my_dog.bark()


    4. The __init__ Method (Constructor) | 构造方法 __init__

    The __init__ method is a special method in Python classes that acts as a constructor. It is automatically called when a new object is created. You use it to initialise instance attributes with values passed as arguments. For example: def __init__(self, name, age): inside a class assigns self.name = name and self.age = age.

    __init__ 方法是 Python 类中用作构造函数的特殊方法。当创建一个新对象时,它会被自动调用。你可以用它来使用传入的参数初始化实例属性。例如,在类中定义 def __init__(self, name, age): 并赋值 self.name = nameself.age = age

    If you do not define an __init__ method, Python provides a default constructor that does nothing. Understanding the role of __init__ is essential for class-based exam questions where you must write or interpret a class definition.

    如果你不定义 __init__ 方法,Python 会提供一个什么都不做的默认构造函数。理解 __init__ 的作用对于基于类的考试题至关重要,这些题目要求你编写或解读类定义。


    5. Encapsulation and Access Control | 封装与访问控制

    Encapsulation is the bundling of data and methods that operate on that data within a single unit (class), and restricting direct access to some of the object’s components. In Python, we use naming conventions to indicate protected and private members: a single leading underscore _ for protected, and double leading underscore __ for private name mangling.

    封装是将数据与操作这些数据的方法捆绑在单个单元(类)中,并限制对对象某些组件的直接访问。在 Python 中,我们使用命名约定来指示受保护成员和私有成员:单下划线前缀 _ 表示受保护,双下划线前缀 __ 会触发名称改写以实现私有。

    Although Python does not enforce strict access modifiers like Java, the convention is respected in Edexcel exam contexts. Getter and setter methods (or properties using the @property decorator) are often used to control access to attributes.

    虽然 Python 不像 Java 那样强制执行严格的访问修饰符,但在 Edexcel 考试情境中,这些约定是被认可的。通常使用 getter 和 setter 方法(或使用 @property 装饰器的属性)来控制对属性的访问。


    6. Inheritance and the ‘is-a’ Relationship | 继承与“是一个”关系

    Inheritance allows a class (child or subclass) to acquire attributes and methods from another class (parent or superclass). This supports code reuse and establishes an ‘is-a’ relationship. In Python, a subclass is created by placing the parent class name in parentheses: class Puppy(Dog):.

    继承允许一个类(子类或派生类)从另一个类(父类或超类)获取属性和方法。这支持代码复用,并建立“是一个”关系。在 Python 中,子类通过将父类名称放在括号中来创建:class Puppy(Dog):

    You can override parent methods by redefining them in the child class. To call the parent’s constructor, use super().__init__(...). Edexcel questions often require you to extend a given class and demonstrate method overriding and the use of super().

    你可以通过在子类中重新定义来覆盖父类方法。要调用父类的构造函数,使用 super().__init__(...)。Edexcel 考题经常要求你扩展一个给定的类,并演示方法覆盖和 super() 的用法。

    Multiple inheritance is possible in Python but can lead to complexity. For Edexcel, focus on single inheritance and understanding how the subclass can add extra attributes or modify behaviour.

    Python 支持多重继承,但可能导致复杂性。对于 Edexcel,重点放在单继承上,并理解子类如何添加额外属性或修改行为。


    7. Polymorphism and Method Overriding | 多态与方法覆盖

    Polymorphism means ‘many forms’. It allows objects of different classes to be treated as objects of a common superclass. The most common form is method overriding, where a subclass provides a specific implementation of a method already defined in its parent. The correct method is invoked based on the object’s actual class at runtime.

    多态意为“多种形态”。它允许将不同类的对象视为公共超类的对象来处理。最常见的形式是方法覆盖,即子类提供对父类中已定义方法的具体实现。运行时根据对象的实际类别调用正确的方法。

    For example, a function that expects an Animal object can work with a Dog or Cat as long as they implement the same method

    Published by TutorHao | A-Level 编程 Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)

  • Object-Oriented Programming Concepts | 面向对象编程概念

    📚 Object-Oriented Programming Concepts | 面向对象编程概念

    Object-Oriented Programming (OOP) is a paradigm that organises software design around data, or objects, rather than functions and logic. An object is a self-contained entity that contains both data in the form of attributes and procedures in the form of methods. This approach models real-world entities, making code more intuitive, reusable, and scalable. In the Edexcel A-Level Computer Science syllabus, understanding OOP is essential for Paper 2, where you are expected to apply these principles in pseudocode and recognise them in Python or other high-level languages.

    面向对象编程是一种将软件设计围绕数据(即对象)而非函数与逻辑来组织的编程范式。对象是一个自包含的实体,包含属性形式的数据和方法形式的操作。这种方法模拟了现实世界实体,使得代码更加直观、可复用且易于扩展。在Edexcel A-Level计算机科学教学大纲中,理解面向对象编程对Paper 2至关重要,你需要能够在伪代码中应用这些原则,并在Python或其他高级语言中识别它们。

    1. Classes and Objects | 类与对象

    A class is a blueprint or template that defines the attributes and behaviours common to a set of objects. An object is a specific instance of a class, created at runtime. For example, a class Car might define attributes like colour and speed, and methods like accelerate(). An object myCar = new Car() would then represent a particular car with its own attribute values. The class provides the structure; the object holds the actual state.

    类是定义一组对象共有属性和行为的蓝图或模板。对象是类的具体实例,在运行时创建。例如,一个 Car 类可能定义了颜色和速度等属性,以及 accelerate() 等方法。而对象 myCar = new Car() 则代表一辆具有自己属性值的特定汽车。类提供了结构,对象持有实际状态。

    2. Encapsulation and Data Hiding | 封装与数据隐藏

    Encapsulation bundles the data (attributes) and the methods that operate on that data into a single unit, the class. It also restricts direct access to some of an object’s internal state. Data hiding is typically achieved using access modifiers such as private, protected, and public. By making attributes private, we force external code to interact with the object only through its public methods, protecting the integrity of the data and reducing unintended interference.

    封装将数据(属性)和操作这些数据的方法捆绑到一个单元,即类中。它还限制了对对象某些内部状态的直接访问。数据隐藏通常通过 private、protected 和 public 等访问修饰符来实现。通过将属性设为 private,我们强制外部代码只能通过对象的公共方法与之交互,从而保护数据的完整性,减少意外的干扰。

    3. Inheritance: Reusing Code | 继承:代码复用

    Inheritance allows a new class (subclass or derived class) to acquire the properties and methods of an existing class (superclass or base class). This promotes code reuse and establishes an ‘is-a’ relationship. For instance, a SportsCar class can inherit from Car, adding a turboBoost() method while automatically having access to accelerate(). Inheritance can be single (one superclass) or multiple (more than one), though many languages like Python support multiple inheritance whereas Java restricts to single inheritance with interfaces.

    继承允许一个新类(子类或派生类)获取已有类(超类或基类)的属性和方法。这促进了代码复用,并建立了“是一个”的关系。例如,一个 SportsCar 类可以从 Car 继承,添加 turboBoost() 方法,同时自动拥有 accelerate() 方法。继承可以是单继承(一个超类)或多继承(多个超类),不过像 Python 这样的语言支持多继承,而 Java 则限定为通过接口实现的单继承。

    4. Polymorphism: Many Forms | 多态:多种形态

    Polymorphism means ‘many forms’ and allows objects of different classes to respond to the same method call in their own specific way. This is often achieved through method overriding, where a subclass provides a tailored implementation of a method already defined in its superclass. Polymorphism enables writing more flexible and generic code. For example, a function can accept a parameter of type Shape and call draw(), and at runtime the correct draw() method of Circle or Rectangle will execute.

    多态意为“多种形态”,允许不同类的对象以各自特定的方式响应同一个方法调用。这通常通过方法重写来实现,即子类提供对超类中已定义方法的定制实现。多态使得代码更加灵活和通用。例如,一个函数可以接受 Shape 类型参数并调用 draw(),运行时将执行 CircleRectangle 正确的 draw() 方法。

    5. Method Overriding vs Overloading | 方法重写与重载

    Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method signature (name and parameters) remains the same, and the decision about which version to invoke is made at runtime (dynamic binding). In contrast, method overloading is defining multiple methods with the same name but different parameter lists within the same class. Overloading is resolved at compile time (static binding) and is not strictly a feature of all OOP languages; Python does not support traditional overloading but can simulate it with default arguments.

    方法重写发生在子类提供对超类中已定义方法的具体实现时。方法签名(名称和参数)保持不变,调用哪个版本的决策在运行时作出(动态绑定)。相比之下,方法重载是在同一个类中定义多个同名但参数列表不同的方法。重载在编译时解析(静态绑定),并非所有面向对象语言都严格支持;Python 不支持传统重载,但可以用默认参数来模拟。

    6. Abstract Classes and Interfaces | 抽象类与接口

    An abstract class is a class that cannot be instantiated and is designed to be subclassed. It may contain abstract methods (without implementation) that subclasses must override. Interfaces define a contract of methods that implementing classes must provide, without any concrete implementation. In Python, the abc module allows creating abstract base classes. Abstract classes and interfaces support polymorphism and enforce a consistent design across a class hierarchy.

    抽象类是不能实例化并设计用于被继承的类。它可以包含抽象方法(无实现),子类必须重写这些方法。接口定义了一组实现类必须提供的方法契约,没有任何具体实现。在 Python 中,abc 模块用于创建抽象基类。抽象类和接口支持多态,并在类层次结构中强制一致的设计。

    7. Association, Aggregation and Composition | 关联、聚合与组合

    These terms describe relationships between classes. Association is a general ‘uses-a’ relationship where objects of one class interact with objects of another. Aggregation is a ‘has-a’ relationship that implies ownership, but the contained object can exist independently (e.g., a Library aggregates Books, but a Book can exist without the Library). Composition is a stronger ‘has-a’ relationship where the contained object cannot exist without the container (e.g., a House is composed of Rooms; destroying the House destroys the Rooms). These concepts are essential for modelling real-world systems.

    这些术语描述了类之间的关系。关联是一种普遍的“使用”关系,一个类的对象与另一个类的对象交互。聚合是一种“拥有”关系,暗示所有权,但所包含对象可以独立存在(例如,图书馆聚合了书籍,但书籍可以脱离图书馆而存在)。组合是一种更强的“拥有”关系,被包含对象不能脱离容器而存在(例如,房子由房间组成;销毁房子也将销毁房间)。这些概念对于现实世界系统建模至关重要。

    8. The Four Pillars of OOP | OOP的四大支柱

    The four fundamental principles of Object-Oriented Programming are encapsulation, inheritance, polymorphism, and abstraction. Abstraction involves hiding complex implementation details and exposing only the essential features of an object. Together, these pillars enable programmers to build modular, maintainable, and robust applications. In your Edexcel exam, you will often be asked to explain these concepts with clear examples, so it is critical to memorise their definitions and demonstrate them in pseudocode.

    面向对象编程的四个基本原则是封装、继承、多态和抽象。抽象涉及隐藏复杂的实现细节,只暴露对象的必要特征。这些支柱共同使程序员能够构建模块化、可维护且健壮的应用程序。在 Edexcel 考试中,你经常会被要求用清晰的例子解释这些概念,因此记住它们的定义并在伪代码中展示它们至关重要。

    9. OOP in Python (Practical Examples) | Python中的OOP实例

    Python is a multi-paradigm language that fully supports OOP. Here is a concise example illustrating class definition, constructor (__init__), instance variables, inheritance, and method overriding:

    Python 是一种全面支持面向对象的多范式语言。以下是一个简洁的示例,展示了类定义、构造方法 (__init__)、实例变量、继承和方法重写:

    class Animal:
        def __init__(self, name):
            self.name = name
        def speak(self):
            return “Some sound”

    class Dog(Animal):
        def speak(self):
            return self.name + ” barks”

    d = Dog(“Fido”)
    print(d.speak()) # Output: Fido barks

    In this code, the subclass Dog inherits from Animal and overrides the speak() method, demonstrating polymorphism. Encapsulation is present with the attribute name accessed via self; you could make it private by prefixing it with double underscores (__name) to enforce data hiding.

    在这段代码中,子类 Dog 继承自 Animal 并重写了 speak() 方法,展示了多态。封装体现在通过 self 访问 name 属性;你可以通过在属性名前加双下划线(__name)将其设为私有以强制数据隐藏。

    10. Advantages and Disadvantages of OOP | 面向对象编程的优缺点

    Advantages include improved modularity, code reusability through inheritance, easier maintenance due to encapsulation, and the ability to model complex real-world systems elegantly. OOP also enables collaborative development because classes can be developed independently. However, disadvantages include a steep learning curve, potential performance overhead, and the tendency to create overly complex class hierarchies. Programs written in an OOP style can sometimes be longer than equivalent procedural code, and analysis of the right object model requires significant effort upfront.

    优点包括更好的模块化、通过继承实现的代码复用性、因封装而更易维护,以及优雅地建模复杂现实世界系统的能力。OOP 还支持协作开发,因为类可以独立开发。然而,缺点包括学习曲线陡峭、潜在的性能开销,以及创建过于复杂的类层次结构的倾向。面向对象风格的程序有时可能比等价的面向过程代码更长,而对正确对象模型的分析需要大量前期工作。

    11. Common OOP Design Patterns | 常见OOP设计模式

    Design patterns are reusable solutions to common software design problems within a given context. Examples include the Singleton pattern that ensures a class has only one instance, the Factory pattern that creates objects without specifying the exact class, and the Observer pattern that defines a one-to-many dependency between objects. While not mandatory for the Edexcel specification, recognising these patterns can deepen your understanding of OOP principles and help in solving complex programming problems.

    设计模式是针对特定上下文中常见软件设计问题的可复用解决方案。例子包括确保一个类只有一个实例的单例模式、无需指定确切类即可创建对象的工厂模式,以及定义对象间一对多依赖关系的观察者模式。虽然这些不属 Edexcel 考试要求范围,但认识这些模式可以加深你对 OOP 原则的理解,并有助于解决复杂编程问题。

    12. Exam Tips for Edexcel A-Level | Edexcel A-Level考试技巧

    When tackling OOP questions in the Edexcel Computer Science examination, always refer to the official pseudocode conventions. Be prepared to write class definitions with attributes, constructors, and methods. Clearly indicate inheritance using the ‘IS A’ relationship in class diagrams or pseudocode. Use access modifiers as specified by the exam board, and illustrate polymorphism by showing how a parent class reference can invoke overridden methods in subclasses. Timed practice with past papers will build confidence, and ensure you can explain concepts in plain English as well as code.

    在应对 Edexcel 计算机科学考试中面向对象的题目时,务必参照官方伪代码规范。准备好编写包含属性、构造方法和方法在内的类定义。在类图或伪代码中清楚用“是一个”关系表示继承。按考试局规定使用访问修饰符,并通过展示父类引用如何调用子类重写的方法来说明多态。用历年真题进行限时练习可以建立信心,并确保你能用通俗英语以及代码来解释概念。


    Published by TutorHao | Computer Science Revision Series | aleveler.com

    更多咨询请联系16621398022(同微信)