Object-oriented programming (OOP) is a fundamental programming paradigm covered in the Edexcel A-Level Computer Science specification. It models real-world entities as objects that contain both data and behaviour, making code more modular, reusable and easier to maintain. This revision guide covers the key OOP concepts you need to master for the exam, including classes, objects, inheritance, polymorphism, encapsulation and design relationships.
1. What is Object-Oriented Programming? | 什么是面向对象编程?
OOP is a programming paradigm based on the concept of objects, which combine data (attributes) and behaviour (methods). Unlike procedural programming, which separates code from data, OOP organises software design around objects that represent real-world entities. This approach improves modularity, reusability and maintainability. Edexcel A-Level focuses on classes, objects, inheritance, polymorphism and encapsulation.
A class is a blueprint or template for creating objects. It defines the attributes and methods that objects of that class will have. An object is an instance of a class, created at runtime. For example, a Car class might define attributes such as colour and speed, and methods such as accelerate() and brake(); a specific object would be a red car with speed 60 km/h.
类是创建对象的蓝图或模板,它定义了该类的对象将具有的属性和方法。对象是类在运行时创建的实例。例如,Car 类可以定义颜色和速度等属性,以及 accelerate() 和 brake() 等方法;一个具体的对象可能是一辆速度为 60 km/h 的红色汽车。
3. Attributes and Methods | 属性和方法
Attributes store the state of an object. They can be instance variables, which belong to each individual object, or class variables, which are shared across all instances. Methods define the behaviour of an object. In Edexcel exams, you may need to identify public and private attributes and explain why private attributes protect data integrity.
Encapsulation means bundling data and methods inside a class and restricting direct access to the internal state. In Python, privacy is indicated by a single underscore convention, while languages like Java use private keyword. Access to private attributes is provided through getter and setter methods. Encapsulation reduces unintended interference and helps maintain invariants.
Inheritance allows a class (subclass) to derive properties and methods from another class (superclass). This supports code reuse and hierarchical classification. For example, Dog and Cat can inherit from Animal, gaining common features such as eat() and sleep(), while adding specific behaviours like bark() or purr(). Edexcel exams often ask about superclasses, subclasses and overriding.
Polymorphism means ‘many forms’. It allows objects of different subclasses to be treated as objects of a common superclass, but the actual method executed is determined at runtime based on the object type. Method overriding is a key mechanism: a subclass provides its own implementation of a method already defined in the superclass. This enables flexible and extensible code.
A constructor is a special method that initialises a new object. In Python, __init__ is called automatically when an object is created. It sets the initial state of the object and can accept parameters. A destructor, such as __del__ in Python, is rarely needed because Python has automatic garbage collection. Exam questions may ask you to write or trace constructor code.
8. Association, Aggregation and Composition | 关联、聚合与组合
These terms describe relationships between classes. Association is a generic ‘uses a’ relationship. Aggregation is a ‘has a’ relationship where the contained object can exist independently, e.g. a Department has Employees. Composition is a stronger ‘has a’ relationship where the part cannot exist without the whole, e.g. a House has Rooms. Recognising these relationships helps design class diagrams.
这些术语描述类之间的关系。关联是一种通用的“使用”关系。聚合是一种“拥有”关系,被包含的对象可以独立存在,例如 Department 拥有 Employees。组合是一种更强的“拥有”关系,部分不能脱离整体而存在,例如 House 拥有 Rooms。识别这些关系有助于设计类图。
9. Static and Class Members | 静态成员与类成员
Static members belong to the class rather than any instance. In Python, class variables and @staticmethod / @classmethod decorators provide this functionality. They are useful for constants, utility functions, and counting instances. In Edexcel exams, static vs instance members may appear in multiple-choice or short-answer questions.
SOLID is a set of five design principles that improve OOP code quality: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation and Dependency Inversion. While A-Level does not require deep implementation, understanding these principles helps answer high-band questions on maintainability, extensibility and code reuse.
11. Practical Example – Bank Account System | 实例分析——银行账户系统
Consider a BankAccount class with private attribute balance, methods deposit(amount) and withdraw(amount), and a subclass SavingsAccount that overrides withdraw to enforce a minimum balance. This example demonstrates encapsulation, inheritance and polymorphism in one small system. Students should be able to identify class relationships and trace method calls.
In Edexcel exams, always use correct terminology: class, object, instance, attribute, method, encapsulation, inheritance, polymorphism. Avoid vague words like ‘thing’ or ‘function’. When explaining advantages, link to maintainability, reusability, security and modularity.
Object-oriented programming (OOP) is a key topic in the Edexcel A-Level Computer Science specification. It moves beyond procedural thinking by grouping data and behaviour into reusable classes. This article explains the concepts, pseudocode patterns and Python examples you need for exam success.
Edexcel A-Level Computer Science asks you to design, trace and evaluate programs using both procedural and object-oriented techniques. OOP questions often require you to identify classes, state their attributes and methods, and suggest improvements using inheritance or encapsulation.
Understanding OOP is not just about writing code. It helps you model real-world problems in a way that is modular, maintainable and exam-friendly. Examiners reward clear class diagrams and concise explanations of how objects interact.
2. Classes and Objects: The Core Building Blocks | 类与对象:核心构建块
A class is a blueprint or template that defines the attributes (data) and methods (behaviour) of a group of similar objects. An object is a specific instance of a class, created at runtime with its own state.
For example, a class called Car might define attributes such as colour and speed, and methods such as accelerate() and brake(). Each Car object can have different values for those attributes.
例如,一个名为 Car 的类可以定义属性如 colour 和 speed,以及方法如 accelerate() 和 brake()。每个 Car 对象可以为这些属性拥有不同的值。
3. Attributes, Methods and Constructors | 属性、方法与构造器
Attributes store the state of an object. In Python, attributes are usually initialised inside a constructor method called __init__. In pseudocode, Edexcel often uses a CLASS … ENDCLASS structure with a constructor like PROCEDURE NEW.
属性存储对象的状态。在 Python 中,属性通常在名为 __init__ 的构造方法内初始化。在伪代码中,Edexcel 通常使用 CLASS … ENDCLASS 结构,并使用类似 PROCEDURE NEW 的构造器。
Methods define what an object can do. A method is simply a function that belongs to a class. Constructor methods run automatically when an object is instantiated, setting up initial values such as default speed or empty lists.
class Car: __init__(self, c, s): self.colour = c; self.speed = s
4. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation means keeping an object’s internal data private and exposing only the necessary methods to the outside world. This prevents invalid states and reduces coupling between parts of a program.
In Python, a single underscore prefix such as _speed indicates that an attribute is intended to be protected. In Edexcel pseudocode, you may see PRIVATE and PUBLIC keywords. Getter and setter methods are used to read and modify private attributes safely.
Inheritance allows a new class to acquire the attributes and methods of an existing class. The new class is called a subclass or derived class, while the existing class is the superclass or base class.
继承允许新类获取现有类的属性和方法。新类称为子类或派生类,而现有类是超类或基类。
Inheritance supports code reuse and represents an ‘is a’ relationship. For example, an ElectricCar class can inherit from Car and add a batteryCapacity attribute and a charge() method.
继承支持代码复用,并表示 ‘is a’ 关系。例如,ElectricCar 类可以继承 Car,并添加 batteryCapacity 属性和 charge() 方法。
class ElectricCar(Car): __init__(self, c, s, b): super().__init__(c, s); self.battery = b
6. Polymorphism: Many Forms of a Method | 多态:方法的多态性
Polymorphism allows methods with the same name to behave differently depending on the object that calls them. This is often achieved through method overriding, where a subclass provides its own implementation of a superclass method.
For example, a Vehicle class may define a move() method. A Car subclass might override move() to print ‘driving on road’, while a Boat subclass prints ‘sailing on water’.
例如,Vehicle 类可以定义 move() 方法。Car 子类可以重写 move() 以输出 ‘driving on road’,而 Boat 子类输出 ‘sailing on water’。
Polymorphism is a common exam focus because it tests whether you understand dynamic method dispatch and how the same interface can hide different underlying behaviours.
多态是常见的考试重点,因为它考查你是否理解动态方法分派,以及同一接口如何隐藏不同的底层行为。
7. Association, Aggregation and Composition | 关联、聚合与组合
Objects do not exist in isolation. Association describes any relationship where one object uses or interacts
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
📚 Edexcel A-Level Programming: From Core Constructs to Algorithm Design | Edexcel A-Level 编程:从核心结构到算法设计
Programming is at the heart of the Edexcel A-Level Computer Science specification. Candidates must be able to trace, write and evaluate code in a high-level language, applying core constructs to solve problems efficiently. This revision guide covers the essential programming techniques, data structures and algorithms you need for both Paper 1 and the practical programming project.
编程是 Edexcel A-Level 计算机科学考试的核心。考生必须能够跟踪、编写和评估高级语言代码,运用核心结构高效地解决问题。本复习指南涵盖 Paper 1 和编程实践项目所需的基本编程技术、数据结构和算法。
1. Sequence, Selection and Iteration | 顺序、选择与迭代
The three fundamental control structures are sequence, selection and iteration. Sequence executes statements in written order; selection uses if, else if and switch-case statements; iteration repeats blocks with for, while and do-while loops. Every program can be built from these three building blocks.
三种基本控制结构是顺序、选择和迭代。顺序按书写顺序执行语句;选择使用 if、else if 和 switch-case 语句;迭代使用 for、while 和 do-while 循环重复代码块。每个程序都可以由这三个基本构件组成。
Edexcel questions often ask you to convert a flowchart or pseudocode into a working program. You must be confident with nested conditions and loop counters, including off-by-one errors. For example, a loop that should run 10 times but uses counter < 10 will stop after 10 iterations, while counter <= 10 will run 11 times.
When tracing nested loops, pay attention to the order in which variables update. The inner loop completes all its iterations for each pass of the outer loop. Questions may ask you to state the final value of a variable or the number of times a print statement executes.
Variables must be declared with an appropriate data type: integer, real/float, Boolean, character and string. Strong typing helps prevent invalid operations and makes code more readable. Choosing the correct type also affects memory usage and arithmetic behaviour.
Type coercion and casting are common pitfalls. For example, dividing two integers in some languages truncates the result, while casting to float preserves the decimal part. You should know how to explicitly convert between types using functions like int(), float() and str().
Constants are named values that do not change during program execution. They improve readability and maintainability. For instance, declaring TAX_RATE = 0.2 is clearer than using the literal 0.2 throughout the code, and it makes updates easier.
Arrays store multiple values of the same type in contiguous memory locations, accessed by an index starting at 0 or 1 depending on the language. Lists are dynamic and can grow or shrink at runtime. In pseudocode, you may see array indices written as arr[0], arr[1] and so on.
Records (or structs) group fields of different types under one name. A record for a student might contain a string name, an integer age and a float average mark. You can create an array of records to store data for many students, and then access fields using dot notation such as student.name.
Two-dimensional arrays are useful for representing grids, tables and matrices. You must be able to read from and write to a cell using row and column indices, for example grid[2][3]. Trace questions often involve nested loops iterating over each row and column.
Functions return a value, while procedures (or subroutines) perform a task without returning a value. Parameters can be passed by value or by reference. Using functions and procedures breaks a large problem into smaller, reusable modules.
Passing by value copies the argument, so the original variable is unchanged. Passing by reference allows the function to modify the caller’s variable, which is useful for returning multiple results. In Edexcel pseudocode, parameters are usually passed by value unless otherwise stated.
Local variables exist only within a function or procedure and are destroyed when it returns. Global variables are accessible throughout the program but can make debugging harder. You should understand the scope of a variable and how it affects side effects and state.
Recursion is a technique where a function calls itself until a base case is reached. Classic examples include factorial n! = n × (n-1)! and Fibonacci numbers. A recursive function must have at least one base case to stop the chain of calls.
递归是一种函数调用自身直到达到基准情形的技术。经典例子包括阶乘 n! = n × (n-1)! 和斐波那契数列。递归函数必须至少有一个基准情形来停止调用链。
Each recursive call is placed on the call stack, storing parameters, local variables and the return address. If the base case is missing or unreachable, a stack overflow occurs. Understanding the call stack helps you trace recursive functions in exam questions.
Recursion can be elegant but may be less efficient than iteration because of the overhead of stack frames. Some problems, such as tree traversal, are naturally recursive, while others can be solved clearly with loops. Edexcel expects you to compare both approaches.
Linear search checks each element in turn and works on unsorted data. Binary search repeatedly halves a sorted array, achieving O(log n) time complexity. You must be able to trace both algorithms and state the number of comparisons made.
Common sorting algorithms include bubble sort, insertion sort and merge sort. Bubble sort compares adjacent items and swaps them if needed; merge sort divides the list and merges sorted halves. Edexcel may ask you to complete a pass of bubble sort or list the steps of a merge.
OOP models real-world entities using classes and objects. A class is a blueprint, while an object is an instance with attributes (fields) and methods. For example, a Car class might have attributes make and speed, and methods accelerate() and brake().
面向对象编程使用类和对象对现实世界实体建模。类是蓝图,而对象是具有属性(字段)和方法(函数)的实例。例如,Car 类可能有属性 make 和 speed,以及方法 accelerate() 和 brake()。
Encapsulation hides internal state and exposes a public interface. Attributes are often declared private and accessed through getter and setter methods. This protects data from invalid changes and makes the class easier to maintain.
Inheritance allows a subclass to reuse and extend a superclass, while polymorphism lets different classes respond to the same method call in their own way. Edexcel questions may ask you to identify the relationship between classes in a UML diagram or code snippet.
Programs often read from and write to text or binary files. Common operations are open, read, write, append and close; closing a file flushes buffers and releases resources. You should know the difference between overwriting a file and appending to the end.
Exceptions handle runtime errors such as file not found, division by zero or invalid user input. A try-except block lets the program recover gracefully instead of crashing. For example, you can catch a FileNotFoundError and prompt the user to enter a valid filename.
Using a finally block ensures that cleanup code runs whether an exception occurred or not. This is especially useful for closing files or database connections. Exam questions sometimes ask you to complete a try-except-finally structure.
In Edexcel A-Level Computer Science, programming is not just about typing code; it is about designing precise, efficient solutions to computational problems. This revision guide covers the core programming techniques you will need for Paper 1 and Paper 2, including data structures, algorithms, recursion, object-oriented principles, and exam strategies.
在爱德思 A-Level 计算机科学中,编程不仅仅是输入代码,更是为计算问题设计精确、高效的解决方案。本复习指南涵盖 Paper 1 和 Paper 2 所需的核心编程技术,包括数据结构、算法、递归、面向对象原则以及考试策略。
1. Computational Thinking and Problem Decomposition | 计算思维与问题分解
Programming in Edexcel A-Level Computer Science begins with computational thinking: decompose a problem into smaller parts, recognise patterns, abstract away irrelevant detail, and design an algorithm before writing code.
A good algorithm must be clear, finite, and precise. It should also be represented using pseudocode, flowcharts, or structured English so that examiners can follow your logic even if syntax is imperfect.
2. Variables, Constants and Data Types | 变量、常量与数据类型
Variables store values that can change while a program runs, whereas constants hold fixed values. Every variable has a data type such as integer, real, Boolean, character, or string, and the choice of type affects memory use and the operations available.
Scope is also important: local variables exist only inside a function or procedure, while global variables can be accessed anywhere. Overusing global variables can make a program harder to debug and maintain.
3. Control Structures: Sequence, Selection, Iteration | 控制结构:顺序、选择与迭代
Sequence means instructions run one after another. Selection uses if, else if, and switch/case to make decisions. Iteration repeats instructions using count-controlled loops such as FOR or condition-controlled loops such as WHILE.
顺序意味着指令一条接一条执行。选择使用 if、else if 和 switch/case 来进行判断。迭代使用计数控制循环(如 FOR)或条件控制循环(如 WHILE)重复执行指令。
Choosing the right loop matters: use a FOR loop when the number of repetitions is known in advance, and a WHILE loop when repetition depends on a condition that may change during execution.
选择合适的循环很重要:当重复次数事先已知时使用 FOR 循环;当重复取决于执行过程中可能变化的条件时使用 WHILE 循环。
4. Functions, Procedures and Parameters | 函数、过程与参数传递
Functions and procedures are named blocks of code that promote modularity and reusability. A function returns a value, while a procedure does not, though both can accept parameters.
Parameters can be passed by value or by reference. Pass by value copies the data, so changes inside the subroutine do not affect the original variable. Pass by reference shares the memory location, allowing the subroutine to modify the caller’s variable.
Recursion is a technique where a function calls itself to solve a smaller version of the same problem. A correct recursive algorithm must have a base case to stop the recursion and a recursive case that moves towards the base case.
For example, the factorial of n can be defined recursively as:
例如,n 的阶乘可以递归定义为:
n! = n × (n − 1)! for n > 1, and 1! = 1
Each recursive call is placed on the call stack. If the base case is missing or unreachable, the stack can overflow, causing a runtime error.
每次递归调用都会放入调用栈。如果缺少基准情形或基准情形不可达,栈可能会溢出,导致运行时错误。
Recursion produces elegant solutions for tree traversal, backtracking, and divide-and-conquer algorithms, but it can be less memory-efficient than iteration.
递归可以为树遍历、回溯和分治算法生成优雅的解决方案,但它可能比迭代占用更多内存。
6. Arrays, Lists and Records | 数组、列表与记录
Arrays store multiple values of the same data type under one name and use an index to access each element. Lists are similar but can often grow and shrink dynamically. Records store fields of different data types about one entity.
A 2D array can model a grid or matrix, such as a game board or a spreadsheet. Accessing an element requires two indices: array[row][column].
二维数组可以模拟网格或矩阵,例如游戏棋盘或电子表格。访问元素需要两个索引:array[行][列]。
Knowing how to traverse arrays with loops, insert and delete elements, and search for a value is essential for Paper 2 algorithmic questions.
了解如何用循环遍历数组、插入和删除元素以及搜索某个值,是 Paper 2 算法题的关键。
7. Sorting and Searching Algorithms | 排序与查找算法
Sorting algorithms arrange data in ascending or descending order. Bubble sort repeatedly compares adjacent items and swaps them if they are in the wrong order. Insertion sort builds a sorted portion by inserting each new item into its correct place.
Merge sort uses divide and conquer: it splits the list in half, sorts each half recursively, and then merges the two sorted halves. This gives a worst-case time complexity of O(n log₂ n), whereas bubble and insertion sorts are O(n²) in the worst case.
Searching can be linear, checking every item one by one, or binary, which works on sorted arrays by repeatedly halving the search interval. Binary search has O(log₂ n) time complexity.
Object-oriented programming (OOP) organises code around classes and objects. A class is a blueprint that defines attributes and methods; an object is an instance of a class.
面向对象编程围绕类和对象组织代码。类是定义属性和方法的蓝图;对象是类的实例。
Encapsulation hides internal state and requires access through methods. Inheritance allows a child class to reuse and extend a parent class. Polymorphism lets different classes respond to the same method name in their own way.
This revision guide covers the programming knowledge required by the Edexcel A-Level Computer Science specification. It includes paradigms, data types, control flow, subroutines, recursion, data structures, algorithms, efficiency, object-oriented design, and testing strategies.
1. Programming Paradigms and Decomposition | 编程范式与问题分解
Edexcel questions often ask you to identify or compare programming paradigms. Procedural programming structures code into procedures or functions that carry out well-defined tasks. Object-oriented programming models real-world entities as classes with attributes and methods. Event-driven programming waits for events such as button clicks, sensor readings, or messages and executes handlers in response.
Procedural — clear sequence of function calls (过程式——清晰的函数调用序列)
Object-oriented — data and behaviour combined in classes (面向对象——数据与行为封装在类中)
Event-driven — non-blocking response to user input (事件驱动——非阻塞响应用户输入)
Decomposition is the process of breaking a large problem into smaller sub-problems. Good decomposition makes code easier to test, debug, reuse, and maintain.
分解是将大问题拆分为更小子问题的过程。良好的分解使代码更易于测试、调试、复用和维护。
2. Data Types, Variables and Constants | 数据类型、变量与常量
You must be confident with primitive data types: integer, real/float, Boolean, character, and string. Edexcel pseudocode uses INTEGER, REAL, BOOLEAN, CHAR and STRING declarations. Variables can change value during execution, whereas constants hold values that cannot be modified after assignment.
Programming is the core problem-solving skill in Edexcel A-Level Computer Science. Whether you are tracing pseudocode in Paper 1 or building a coursework project, a secure grasp of constructs, data structures, algorithms and testing will directly determine your marks.
编程是 Edexcel A-Level 计算机科学的核心问题解决技能。无论你是在 Paper 1 中追踪伪代码,还是在课程项目中构建程序,对结构、数据结构、算法和测试的扎实掌握都会直接影响你的得分。
1. Programming Fundamentals | 编程基础
Every Edexcel A-Level programming answer depends on three building blocks: sequence, selection and iteration. Sequence means instructions execute one after another; selection uses IF…THEN…ELSE…ENDIF or CASE statements; iteration is implemented with FOR, WHILE or REPEAT…UNTIL loops.
Use constants for fixed values so programs are easier to maintain, and choose meaningful variable names such as totalScore rather than ts. Comments should explain why a complex step exists, not simply repeat the code.
In Edexcel pseudocode, assignment is written with the left arrow ←. For example, total ← total + mark updates a running total by adding the current mark.
在 Edexcel 伪代码中,赋值使用左箭头 ←。例如,total ← total + mark 通过加上当前分数更新累计总分。
2. Data Types and Structures | 数据类型与结构
Edexcel pseudocode uses integer, real, char, string and Boolean data types. Integer arithmetic truncates division results, while real arithmetic keeps the fractional part.
📚 Edexcel A-Level Programming Essentials: Data, Control and Algorithms | Edexcel A-Level 编程核心:数据、控制与算法
Programming questions in Edexcel A-Level Computer Science are not only about writing code. You need to be confident with data types, variables, control structures, subroutines and standard algorithms, and you need to express your thinking clearly in pseudocode.
A programming paradigm is a style of programming. Edexcel expects you to identify procedural, object-oriented, event-driven and functional paradigms, and to compare their strengths for a given scenario.
Procedural programming uses a clear sequence of instructions and subroutines. Object-oriented programming uses classes and objects to model data and behaviour. Event-driven programming waits for events such as mouse clicks or key presses.
Selecting the correct data type avoids unnecessary memory use and makes operations predictable. The main types you need are integer, real/float, Boolean, character, string and sometimes date/time.
📚 Object-Oriented Programming in Python: Classes, Inheritance and Polymorphism | Python 面向对象编程:类、继承与多态
Object-oriented programming (OOP) is a core topic in the Edexcel A-Level Computer Science specification, particularly within Topic 4: Programming. This article explains the key OOP concepts in Python: classes, objects, encapsulation, inheritance, and polymorphism.
1. Introduction to Object-Oriented Programming | 面向对象编程简介
Object-oriented programming is a paradigm that organises code around ‘objects’ rather than functions and logic alone. An object bundles data and the functions that operate on that data into a single unit.
The main benefits of OOP include easier maintenance, code reuse through inheritance, and the ability to model real-world entities more naturally. For A-Level exams, you need to explain these advantages and identify the building blocks: class, object, attribute, method, constructor, encapsulation, inheritance, and polymorphism.
A class is a blueprint or template for creating objects. An object is an instance of a class. For example, the class Student defines the general properties and behaviours of all students, while each individual student is an object of that class.
In Python, you define a class using the class keyword followed by the class name and a colon. The body of the class contains method definitions with an indented block. The simplest class can be written as class Student: pass.
在 Python 中,使用 class 关键字后跟类名和冒号来定义类。类的主体包含缩进的方法定义。最简单的类可以写作 class Student: pass。
Class = blueprint (e.g. Student)
Object = a real instance (e.g. Alice, Bob)
Class = 蓝图(例如学生)
Object = 真实实例(例如 Alice、Bob)
3. The __init__ Constructor and self | __init__ 构造器与 self
The __init__ method is a special constructor that runs automatically when an object is created. It initialises the object’s attributes with values passed as arguments.
__init__ 方法是一个特殊的构造器,在创建对象时自动运行。它用传入的参数值初始化对象的属性。
Inside every instance method, the first parameter self refers to the current object. Using self.name = name stores the parameter value into the object’s own attribute, so different objects keep separate data.
在每个实例方法内部,第一个参数 self 指向当前对象。使用 self.name = name 将参数值存入对象自身的属性,从而使不同对象保存各自独立的数据。
Attributes are variables that belong to an object, and methods are functions that belong to an object. In a class, attributes are usually defined inside __init__, while methods are defined as functions inside the class body.
There are two types of attributes: instance attributes (unique to each object, using self.) and class attributes (shared by all objects, written directly inside the class). A-level exam questions often ask you to distinguish between these.
For example, a class attribute school = 'Aleveler College' is the same for all objects, while self.name is different for each student. Accessing an attribute is done with dot notation: object.attribute.
例如,类属性 school = 'Aleveler College' 对所有对象都是相同的,而 self.name 每个学生不同。使用点号访问属性:对象.属性。
5. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation means hiding the internal state of an object and requiring all interaction to go through public methods. This protects data from being changed in unexpected ways and makes the code easier to debug.
In Python, encapsulation is implemented by naming conventions rather than strict access modifiers. A single leading underscore (_attribute) signals ‘protected’, while a double leading underscore (__attribute) triggers name mangling to make it harder to access from outside the class.
To provide controlled access, use getter and setter methods. For example, a get_age() method returns the age, and a set_age(new_age) method validates input before changing the value. The @property decorator can make getters and setters look like normal attribute access.
6. Inheritance: Building Class Hierarchies | 继承:构建类层次结构
Inheritance allows a new class (child or subclass) to reuse the attributes and methods of an existing class (parent or superclass). This supports code reuse and models ‘is-a’ relationships, such as a Dog is an Animal.
继承允许新类(子类)重用现有类(父类或超类)的属性和方法。这支持代码复用,并模拟“is-a”关系,例如 Dog 是一个 Animal。
In Python, a subclass is defined by placing the parent class name in parentheses: class Dog(Animal):. The subclass automatically inherits all methods and attributes from the parent, but it can also add new ones or override existing ones.
Exam questions may ask you to identify the superclass, subclass, and inherited members from a given code snippet, or to write a subclass that extends a given parent correctly.
考试题可能会要求你从给定代码片段中识别超类、子类和继承的成员,或者编写一个正确扩展给定父类的子类。
7. Method Overriding and the super() Function | 方法重写与 super() 函数
Method overriding occurs when a subclass defines a method with the same name as a method in its parent class. The subclass version replaces the parent version for objects of the subclass, allowing more specific behaviour.
If you need to call the parent class’s version from within the overridden method, use the super() function. For example, super().__init__(name) calls the parent constructor before adding subclass-specific initialisation.
Using super() avoids duplicating code and ensures that the parent’s initialisation or validation still runs. This is a common pattern in object-oriented Python and appears frequently in A-level coding questions.
Polymorphism means ‘many forms’. In OOP, it allows different classes to provide their own implementation of the same method name, so the same code can work with objects of different types.
Python uses duck typing: if an object has the required method, it can be used regardless of its class. The saying ‘if it walks like a duck and quacks like a duck, then it is a duck’ summarises this idea.
For example, both Circle and Square classes may define an area() method. A function that calls shape.area() works with either class, demonstrating polymorphic behaviour without inheritance.
An abstract base class is a class that cannot be instantiated; its purpose is to define a common interface for subclasses. In Python, the abc module provides the ABC class and the @abstractmethod decorator.
Any subclass of an abstract class must override all abstract methods, otherwise the subclass also becomes abstract and cannot be instantiated. This enforces a contract for all derived classes.
For Edexcel A-Level, you should be able to recognise the purpose of abstract classes and explain why they are useful in designing large programs with consistent interfaces.
10. OOP vs Procedural Programming: Exam Perspective | OOP 与过程式编程:考试视角
Procedural programming organises code as a sequence of instructions and functions, while OOP organises code as interacting objects. Both paradigms can solve the same problems, but OOP is often preferred for large, complex systems because it improves modularity and maintainability.
In exam questions, you may be asked to compare the two paradigms, identify which is more suitable for a given scenario, or convert a short procedural script into an object-oriented version using classes and methods.
Remember the key terms and their definitions: class, object, attribute, method, constructor, inheritance, polymorphism, encapsulation, and abstract class. Practise writing short Python class definitions by hand, because Edexcel coding questions often expect you to write or complete code in the exam.
📚 Programming Fundamentals and Algorithms for Edexcel A-Level | Edexcel A-Level 编程基础与算法精讲
Programming is a central component of the Edexcel A-Level Computer Science specification. It tests your ability to design, write, trace and evaluate code under exam conditions. This revision guide brings together the essential constructs, data structures, standard algorithms and object-oriented techniques you need to succeed in Paper 2 and the practical programming project.
编程是 Edexcel A-Level 计算机科学考试的核心组成部分。它考查你在考试条件下设计、编写、追踪和评估代码的能力。本复习指南汇总了你在 Paper 2 和实践编程项目中取得成功所需的基本结构、数据结构、标准算法与面向对象技术。
1. Variables, Data Types and Constants | 变量、数据类型与常量
In Edexcel pseudocode and Python, a variable is a named memory location whose value can change during execution. Constants are fixed values declared with the keyword CONSTANT, and their identifiers are usually written in upper case.
Common data types include Integer, Real/Float, Boolean, Char, String, and Date. Choosing the correct type affects memory use and the operations available; for example, string concatenation uses ‘+’ while integer division uses DIV or //.
常见数据类型包括整型、实型/浮点型、布尔型、字符型、字符串型和日期型。选择正确的类型会影响内存使用和可用的操作;例如,字符串连接使用 ‘+’,而整数除法使用 DIV 或 //。
Arithmetic operators include +, -, *, /, MOD and DIV. Comparison operators are =, ≠, <, >, ≤ and ≥. Type conversion functions such as INT_TO_STRING and STRING_TO_INT are useful when handling user input.
All algorithms can be built from three control structures: sequence, selection and iteration. Sequence executes statements one after another; selection uses IF…THEN…ELSE…ENDIF to make decisions; iteration repeats blocks using FOR, WHILE or REPEAT…UNTIL loops.
When choosing between loops, remember that a WHILE loop tests the condition before each iteration and may never execute, whereas a REPEAT…UNTIL loop tests after each iteration and executes at least once.
在循环之间选择时,请记住 WHILE 循环在每次迭代之前测试条件,可能一次都不执行;而 REPEAT…UNTIL 循环在每次迭代之后测试条件,至少执行一次。
A CASE statement can replace multiple IF…ELSEIF checks when the same variable is compared with several literal values. Nested structures are allowed, but deep nesting reduces readability and should be avoided where possible.
IF score ≥ 80 THEN grade ← ‘A’ ELSE IF score ≥ 60 THEN grade ← ‘B’ ELSE grade ← ‘C’ ENDIF
3. Arrays, Lists and 2D Structures | 数组、列表与二维结构
Arrays and lists store multiple values under one identifier. A 1D array is indexed from 0 in Python or from 1 in some pseudocode; Edexcel pseudocode often uses 0-based indexing, so always check the question context.
Common operations on arrays include traversing, inserting, deleting and searching. Inserting or deleting in the middle of an array requires shifting elements, which has O(n) time complexity.
A 2D array is a table of rows and columns, written as myArray[row, column]. Use nested loops to traverse it, with the outer loop controlling rows and the inner loop controlling columns.
FOR i ← 0 TO rows-1 FOR j ← 0 TO cols-1 OUTPUT myArray[i, j] NEXT j NEXT i
4. Functions and Procedures | 函数与过程
Functions return a value and are called as part of an expression; procedures do not return a value and are called as standalone statements. Parameters can be passed by value or by reference, which affects whether changes persist outside the subroutine.
Local variables are declared inside a subroutine and exist only during its execution. Global variables can be accessed anywhere, but overusing them makes code harder to debug and reduces modularity.
By default, scalar parameters are passed by value in most languages, meaning a copy is made. Arrays and objects are often passed by reference, so changes inside the subroutine can affect the original data structure.
A recursive subroutine calls itself with a smaller instance of the problem. Every recursive algorithm must have a base case to stop the recursion and a recursive case that reduces the problem size.
Recursion uses the call stack to store return addresses and local variables. If the base case is missing or unreachable, the stack overflows, causing a runtime error.
递归使用调用栈来存储返回地址和局部变量。如果基本情况缺失或无法到达,栈会溢出,导致运行时错误。
Recursion often produces elegant solutions for problems such as factorial, Fibonacci and binary tree traversal. However, recursion can be less efficient than iteration because each call adds stack overhead and may recompute the same values.
FUNCTION Factorial(n) IF n = 0 THEN RETURN 1 ELSE RETURN n × Factorial(n-1) ENDIF END FUNCTION
6. File Handling and Exception Management | 文件处理与异常管理
External data is stored in text or binary files. Typical operations include opening a file in read, write or append mode, reading lines with READLINE, writing with PRINT or WRITELINE, and closing the file with CLOSE.
外部数据存储在文本或二进制文件中。典型操作包括以读、写或追加模式打开文件,用 READLINE 读取行,用 PRINT 或 WRITELINE 写入,以及用 CLOSE 关闭文件。
Always close files after use to flush buffers and release file handles. The EOF marker indicates the end of a file, and loops should stop reading when EOF is reached.
Exception handling uses TRY…EXCEPT…FINALLY to manage runtime errors such as a missing file or invalid numeric input. This prevents the program from crashing and allows graceful recovery.
TRY OPEN ‘data.txt’ FOR READ WHILE NOT EOF READLINE ENDWHILE EXCEPT IOError OUTPUT ‘File not found’ FINALLY CLOSE FILE ENDTRY
7. Searching Algorithms: Linear and Binary Search | 查找算法:线性搜索与二分搜索
Linear search checks each element in turn until the target is found or the list ends. It works on unsorted data and has a worst-case time complexity of O(n).
Binary search repeatedly halves a sorted list by comparing the middle element with the target. It has O(log₂ n) time complexity but requires the data to be sorted first.
In a binary search, if the target is less than the middle value, discard the upper half; if greater, discard the lower half. This process continues until the target is found or the search interval is empty.
Bubble sort compares adjacent pairs and swaps them if they are out of order, moving the largest value to the end on each pass. It is stable but inefficient with O(n²) average time.
Insertion sort builds a sorted sublist by inserting each new element into its correct position. It performs well on nearly sorted data and is also stable.
Merge sort uses a divide-and-conquer approach, recursively splitting the list in half, sorting each half, and merging the results. It guarantees O(n log₂ n) time but uses extra memory.
A stable sorting algorithm preserves the relative order of equal elements. This matters when sorting by one key and then another, such as sorting students by name and then by grade.
9. Big O Notation and Algorithm Efficiency | 大 O 表示法与算法效率
Big O notation describes how the time or space required by an algorithm grows as the input size n increases. Constant time is O(1), linear is O(n), quadratic is O(n²), and logarithmic is O(log₂ n).
大 O 表示法描述算法所需的时间或空间如何随着输入规模 n 的增长而增长。常数时间为 O(1),线性为 O(n),二次方为 O(n²),对数为 O(log₂ n)。
In an exam, you may be asked to compare algorithms for the same task. Always consider the best, average and worst cases, and whether extra memory is required.
在考试中,你可能会被要求比较解决同一任务
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
Programming in the Edexcel A-Level Computer Science specification is not just about writing code; it demands a precise understanding of language constructs, data representation, control flow and algorithm efficiency. This article consolidates the core programming concepts that frequently appear in Paper 1 and Paper 2 questions, with worked explanations and common exam traps.
1. Programming Paradigms and Language Types | 编程范式与语言类型
Edexcel expects candidates to distinguish between imperative, object-oriented, functional and logic paradigms. Imperative code uses sequences, selection and iteration to change program state; object-oriented code organises state and behaviour into classes and objects; functional code treats computation as evaluation of mathematical functions and avoids side effects; logic programming expresses rules and queries.
High-level languages are translated by compilers or interpreters. A compiler translates the whole source code into machine code before execution, while an interpreter translates and executes line by line. Bytecode languages such as Java use both: source code is compiled to bytecode, then interpreted or just-in-time compiled by a virtual machine.
2. Data Types, Variables and Constants | 数据类型、变量与常量
Programs store values in variables and constants. Primitive data types include integer, real/floating-point, Boolean, character and string. Edexcel questions often test type conversion, overflow, and the difference between assignment and comparison (for example = vs == in many languages).
Constants are declared with a fixed value that cannot change during execution, improving maintainability and reducing magic numbers. Variables should have meaningful identifiers and appropriate scope: local variables exist only inside a function or block; global variables exist throughout the program but can make debugging harder.
3. Control Structures: Sequence, Selection, Iteration | 控制结构:顺序、选择与迭代
All procedural programs are built from three control structures: sequence, selection and iteration. Selection is implemented with IF, ELSE IF, ELSE or switch/case statements. Nested selection must use clear indentation and Boolean operators such as AND, OR, NOT.
Iteration includes definite loops, such as FOR loops that run a known number of times, and indefinite loops, such as WHILE and REPEAT…UNTIL. WHILE loops test the condition before each iteration and may run zero times; REPEAT…UNTIL loops test after each iteration and always run at least once.
迭代包括确定循环(如已知运行次数的 FOR 循环)和不确定循环(如 WHILE 和 REPEAT…UNTIL)。WHILE 循环在每次迭代前测试条件,可能一次也不运行;REPEAT…UNTIL 循环在每次迭代后测试条件,因此至少运行一次。
WHILE score < 0 OR score > 100 OUTPUT “Invalid score, re-enter: “ INPUT score ENDWHILE
4. Functions, Procedures and Parameters | 函数、过程与参数
A function returns a value; a procedure performs a task but does not return a value. Both help decompose large problems into smaller, reusable modules. Parameters allow values to be passed into a subprogram.
There are two main parameter passing methods: by value and by reference. Pass by value copies the argument, so changes inside the subprogram do not affect the original variable. Pass by reference passes the address, so changes modify the original. Edexcel pseudocode may use keywords such as BYVAL and BYREF.
Recursion is a technique where a function calls itself. Every recursive algorithm must have a base case to stop the recursion and a recursive case that reduces the problem size. For example, factorial n = n × (n−1)! with base case 0! = 1.
递归是一种函数调用自身的技术。每个递归算法必须有停止递归的基准情形,以及减小问题规模的递归情形。例如,阶乘 n = n × (n−1)!,基准情形为 0! = 1。
n! = n × (n − 1)! for n > 0, with 0! = 1
5. Recursion and Stack Frames | 递归与栈帧
When a recursive function runs, each call creates a new stack frame containing its parameters and local variables. These frames are pushed onto the call stack. If the base case is missing or unreachable, the stack overflows and the program crashes.
Recursion can produce elegant solutions for tree traversal, binary search and divide-and-conquer algorithms. However, it can be less efficient in memory than iteration because of the stack usage. Some problems, such as Fibonacci, have overlapping subproblems, so recursion without memoisation repeats work.
6. Data Structures: Arrays, Lists, Stacks and Queues | 数据结构:数组、列表、栈与队列
Arrays store elements of the same type in contiguous memory locations and allow direct access by index in O(1) time. Static arrays have a fixed size, while dynamic arrays can resize. A 2D array is often used to represent tables or matrices.
Stacks and queues are abstract data types. A stack is a LIFO (last in, first out) structure with push and pop operations; it is used in expression evaluation, backtracking and call stacks. A queue is a FIFO (first in, first out) structure with enqueue and dequeue operations; it is used in scheduling and breadth-first search.
Object-oriented programming (OOP) models real-world entities as objects. A class is a blueprint that defines attributes (data) and methods (behaviours). An object is an instance of a class. Encapsulation hides internal state and exposes only necessary methods.
Inheritance allows a subclass to reuse and extend the attributes and methods of a superclass, promoting code reuse and polymorphism. Polymorphism lets different classes respond to the same method name in different ways. Composition is often preferred over deep inheritance because it is more flexible.
8. Error Handling, Validation and Testing | 错误处理、验证与测试
Robust programs anticipate invalid input and runtime errors. Input validation checks data against rules such as range, type, length and format. Edexcel questions may ask you to write pseudocode that uses WHILE loops for validation, or to identify logic, syntax and runtime errors.
健壮的程序会预判无效输入和运行时错误。输入验证根据范围、类型、长度和格式等规则检查数据。Edexcel 题目可能要求你编写使用 WHILE 循环进行验证的伪代码,或识别逻辑错误、语法错误和运行时错误。
Testing strategies include normal, boundary and erroneous test data. Boundary values such as minimum, maximum, just below and just above a limit often reveal off-by-one errors. Trace tables are used to track variable values line by line and locate faults.
9. Algorithm Analysis and Big O Notation | 算法分析与大 O 表示法
Algorithm efficiency is measured by time and space complexity. Big O notation describes the upper bound of growth as input size n increases. 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ⁿ)。
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
📚 Mastering Edexcel A-Level Programming: From Core Constructs to Algorithms | 精通Edexcel A-Level编程:从核心结构到算法
This article consolidates the core programming ideas assessed in Edexcel A-Level Computer Science. It is suitable for revision of Paper 2 topics and for strengthening your programming project skills.
1. Variables, Constants and Data Types | 变量、常量与数据类型
A variable is a named storage location whose value can change during execution. A constant is fixed once assigned, and using constants improves maintainability by preventing accidental modification.
Edexcel pseudocode commonly uses the five standard data types: Integer, Real/Float, Boolean, Character, and String. Choosing the correct type affects memory usage and the operations that can be performed.
Type conversions may be implicit or explicit. In many languages, dividing two integers may produce a real result, while explicit casting such as INT(3.7) truncates the decimal part.
Selection uses IF…THEN…ELSE constructs to choose between alternative paths. Nested IF statements can express multi-branch logic, but CASE/SWITCH structures are often clearer.
Iteration repeats a block of code. Definite iteration (FOR loops) runs a known number of times, while indefinite iteration (WHILE and REPEAT…UNTIL) continues until a condition changes.
When comparing loop types, remember that a WHILE loop checks the condition at the start, so it may execute zero times. A REPEAT…UNTIL loop checks at the end, so the body always runs at least once.
An array is a finite, ordered collection of elements of the same data type. Arrays allow direct access by index, usually starting at 0, which gives O(1) read/write time.
Lists are dynamic structures that can grow and shrink. They support insertion and deletion more flexibly than static arrays, though access to an element by position may be O(n) in a linked implementation.
A record combines fields of different types under one name, such as a Student record containing name, age and grade. It is a simple way to model real-world entities.
Parameters can be passed by value or by reference. By value copies the argument, so changes inside the routine do not affect the original. By reference passes the address, so modifications persist.
Using meaningful identifiers, local variables and clear pre/post-conditions makes subroutines easier to test and reuse. Modular programming supports divide-and-conquer problem solving.
A recursive subroutine calls itself with a smaller input. Every valid recursive solution needs a base case to stop the recursion and a recursive case that moves toward the base case.
Each recursive call is placed on the call stack. The stack stores return addresses, parameters and local variables. If the base case is missing or unreachable, stack overflow can occur.
Recursion can be elegant for problems such as factorial, Fibonacci and tree traversal, but it may use more memory than an equivalent iterative solution.
递归对于阶乘、斐波那契和树遍历等问题可能十分简洁,但它可能比等价的迭代方案使用更多内存。
6. Searching Algorithms: Linear and Binary Search | 搜索算法:线性搜索与二分搜索
Linear search checks each element in order. It works on unsorted data and has O(n) worst-case time. Binary search requires sorted data and repeatedly halves the search interval.
For binary search, compare the target with the middle element. If it is smaller, search the left half; if larger, search the right half. The maximum number of comparisons is about log₂ n + 1.
对于二分搜索,将目标值与中间元素比较。如果目标较小则搜索左半部分;如果较大则搜索右半部分。最大比较次数约为log₂ n + 1。
Binary search time = O(log n)
二分搜索时间 = O(log n)
7. Sorting Algorithms: Bubble, Insertion and Merge Sort | 排序
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
Object-oriented programming is a central paradigm in the Edexcel A-Level Programming unit, requiring learners to move beyond linear scripts and design software using interacting objects. This article revises the core OOP principles, common syntax patterns and the assessment style you can expect in the exam.
In the Edexcel A-Level Programming specification (Paper 2 or Unit 2 depending on your pathway), OOP is assessed through short-answer questions, trace-table tasks, and extended responses that ask you to design or evaluate class hierarchies.
Typical mark allocations range from 1-mark definitions of keywords such as ‘encapsulation’ to 6-mark questions comparing inheritance with composition.
典型分值从关键词定义(如”封装”)的 1 分题,到比较继承与组合的 6 分题不等。
You should be confident writing basic class skeletons, identifying errors in given code, and explaining how OOP principles improve maintainability.
你应该能熟练编写基本类框架、识别给定代码中的错误,并解释 OOP 原则如何提高可维护性。
2. From Procedural to Object-Oriented | 从过程式到面向对象
Procedural programming organises code as a sequence of instructions and reusable functions, while OOP bundles data and behaviour together into classes.
过程式编程将代码组织为一系列指令和可复用函数,而面向对象编程将数据和行为捆绑到类中。
The key difference is that an object has state (attribute values) and behaviour (methods) that act on that state, allowing more natural modelling of real-world systems.
关键区别在于对象具有状态(属性值)和行为(作用于状态的方法),从而更自然地建模现实世界系统。
For example, a BankAccount object can have a balance attribute and deposit() and withdraw() methods, rather than passing a balance variable to separate functions.
There are also class attributes (static fields) shared by all instances, but instance attributes are the most common exam focus.
还有由所有实例共享的类属性(静态字段),但实例属性是最常见的考试重点。
5. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation means keeping an object’s internal data private and providing controlled access through public methods, often called getters and setters.
This protects the integrity of the data because validation can be placed inside the setter, preventing impossible states such as a negative age.
这保护了数据的完整性,因为可以在 setter 中加入验证,防止出现负年龄等不可能的状态。
Java uses private, public and protected keywords, while Python conventionally uses a single underscore prefix (_balance) to signal ‘protected’ but does not enforce it strictly.
In exams, you may be asked to explain why directly exposing attributes is considered poor practice and how encapsulation supports validation and maintenance.
考试中可能会要求你解释为什么直接暴露属性是不良实践,以及封装如何支持验证和维护。
6. Constructors and Instantiation | 构造函数与实例化
A constructor is a special method that initialises a new object, setting the initial values of attributes.
构造函数是一种特殊方法,用于初始化新对象,设置属性的初始值。
In Python, the constructor is named __init__ and takes self as the first parameter, e.g. def __init__(self, name, age): self.name = name.
Default constructors are provided automatically if no constructor is written, but once you define a parameterised constructor the default disappears unless you write it again.
Constructors of subclasses must call the superclass constructor, using super().__init__(…) in Python or super(…) in Java, to ensure inherited attributes are set up.
Polymorphism means ‘many forms’ and allows the same method call to behave differently depending on the object’s actual class.
多态意为”多种形态”,允许相同的方法调用根据对象的实际类表现出不同的行为。
Method overriding occurs when a subclass defines a method with the same signature as a superclass method, replacing its implementation for subclass objects.
方法重写发生在子类定义与超类方法签名相同的方法时,为子类对象替换该方法的实现。
For example, a list of Shape objects may contain Circle and Square instances, and calling shape.area() dispatches to the correct override at runtime.
例如,一个 Shape 对象列表可能包含 Circle 和 Square 实例,调用 shape.area() 在运行时分派到正确的重写方法。
In Python, polymorphism is achieved dynamically by simply defining a method with the same name; in Java, use @Override annotation for clarity.
在 Python 中,多态通过动态地定义同名方法实现;在 Java
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
📚 Programming Fundamentals: Variables, Data Types and Control Structures | 编程基础:变量、数据类型与控制结构
In Edexcel A Level Computer Science, the ‘Programming’ topic focuses on the building blocks needed to design and write reliable programs. This article summarises variables, data types, control structures, subroutines, and recursion, with clear links to pseudocode and the assessment objectives.
在 Edexcel A Level 计算机科学中,“编程”主题聚焦于设计和编写可靠程序所需的基础构件。本文总结变量、数据类型、控制结构、子程序与递归,并结合伪代码与考核目标进行讲解。
1. Variables and Constants | 变量与常量
In programming, a variable is a named location in memory that stores a value. The value can be read, updated, or used in expressions. Most languages require a variable to be declared before use, and some require an explicit data type.
A constant is a value that remains unchanged throughout the execution of a program. In pseudocode, constants are often declared using the keyword CONST. They help avoid ‘magic numbers’ in code.
Variables are mutable; constants are immutable. | 变量可变;常量不可变。
Always initialise variables before reading them. | 读取变量前务必先初始化。
Use meaningful names such as customerAge rather than x. | 使用有意义的名称,如 customerAge,而不是 x。
2. Primitive Data Types | 原始数据类型
Primitive data types are the basic categories of value that a programming language provides. The most common types are integer, real (floating-point), Boolean, and character.
原始数据类型是编程语言提供的基本值类别。最常见的类型有整型、实数型(浮点型)、布尔型和字符型。
Each type uses a different amount of memory and supports different operations. For example, integers support whole-number arithmetic, while reals support fractional arithmetic.
📚 Operators and Expressions in Programming | 编程中的运算符与表达式
Operators are the symbols that tell a computer to perform specific mathematical, relational or logical operations. In Edexcel A-Level Computer Science, you must be able to read, write and trace expressions that combine operators and operands.
Operators form the core of every executable instruction. Without them, a program could store data but never calculate, compare or decide.
运算符构成了每条可执行指令的核心。没有它们,程序只能存储数据,却无法计算、比较或做出决策。
Arithmetic operators build formulas for prices, coordinates and counters. 算术运算符用于为价格、坐标和计数器构建公式。
Comparison operators drive conditional statements such as IF and WHILE. 比较运算符驱动 IF 和 WHILE 等条件语句。
Logical operators combine multiple true/false conditions in selection. 逻辑运算符在选择结构中组合多个真/假条件。
2. Arithmetic Operators | 算术运算符
The usual arithmetic operators are addition, subtraction, multiplication, division, modulus, integer division and exponentiation. In Python they are written +, -, *, /, %, //, **.
and returns True only if both operands are True. and 仅当两个操作数都为 True 时才返回 True。
or returns True if at least one operand is True. or 只要有一个操作数为 True 就返回 True。
not reverses the Boolean value. not 反转布尔值。
(age >= 18) and (country == ‘UK’)
The expression above is True only when both the age condition and the country condition are True.
上面的表达式仅当年龄条件和国家条件都为 True 时才为 True。
5. Bitwise Operators | 位运算符
Bitwise operators work on binary representations of integers. They are less common in A-Level exams, but you may need to trace bit-level operations such as AND, OR, XOR, NOT, left shift and right shift.
Example: 5 & 3 = 1 because 0101 and 0011 produce 0001.
示例:5 & 3 = 1,因为 0101 与 0011 得到 0001。
6. Assignment Operators | 赋值运算符
The basic assignment operator is =. Compound assignment operators combine arithmetic with assignment, which shortens code.
基本赋值运算符是 =。复合赋值运算符将算术与赋值结合起来,可以缩短代码。
x += 5 is equivalent to x = x + 5. x += 5 等价于 x = x + 5。
x *= 2 is equivalent to x = x * 2. x *= 2 等价于 x = x * 2。
x //= 3 and x %= 3 behave similarly for integer division and remainder. x //= 3 和 x %= 3 分别类似地执行整除和取余。
7. Membership and Identity Operators | 成员与身份运算符
Membership operators test whether a value exists in a sequence. Identity operators test whether two references point to the same object in memory.
成员运算符测试一个值是否存在于序列中。身份运算符测试两个引用是否指向内存中的同一个对象。
in returns True if the element is present in a list, string or tuple. in 如果元素存在于列表、字符串或元组中,则返回 True。
not in returns True if the element is absent. not in 如果元素不存在,则返回 True。
is checks identity; == checks equality of value. is 检查身份;== 检查值的相等性。
8. Precedence and Associativity | 优先级与结合性
Operator precedence decides the order in which operations are evaluated. In most languages, brackets have the highest priority, then exponent, then multiplication/division, then addition/subtraction, then comparisons, then logical operators.
Object-oriented programming (OOP) is a central programming paradigm in the Edexcel A-Level Computer Science specification. It organises code into classes and objects, making programs easier to design, maintain and reuse. This article explains the key OOP concepts you need to master, from classes and objects to inheritance and polymorphism, with exam-focused examples.
1. Programming Paradigms: Where OOP Fits | 编程范式:OOP 的定位
Before studying OOP, it is useful to compare it with other paradigms. Procedural programming uses sequences of instructions and functions; functional programming treats computation as evaluation of mathematical functions; OOP models a system as interacting objects. Edexcel questions often ask you to justify choosing an OOP approach.
The table summarises the three main paradigms. In an exam, if a scenario describes multiple entities such as students, teachers and courses, OOP is usually the natural choice because it binds data and behaviour together in objects.
A class is a blueprint or template that defines the attributes (data) and methods (behaviour) common to a group of objects. An object is a specific instance of a class. For example, a class Car might have attributes such as registration, make and colour, and methods such as accelerate() and brake(). The object myCar = Car(“AB12 CDE”, “Toyota”, “blue”) is one concrete instance.
CLASS Car ATTRIBUTES registration, make, colour METHODS accelerate(), brake() ENDCLASS
In Edexcel-style pseudocode, class definitions often look like the structure above. The exact syntax is less important than recognising that attributes hold data and methods define behaviour.
Attributes store the state of an object, while methods define the operations that can be performed on that state. In Edexcel pseudocode, attributes are often declared inside a class and methods are procedures or functions that belong to the class. You should be able to identify which items in a scenario become attributes and which become methods.
For example, in a bank account scenario, the balance is an attribute because it is data, while deposit() and withdraw() are methods because they change or inspect the balance. A common exam task is to list suitable attributes and methods for a given class.
Encapsulation means hiding the internal state of an object and requiring all interaction to go through methods. This protects data from accidental corruption and allows the internal implementation to change without affecting other parts of the program. In OOP languages, access modifiers such as private and public control visibility.
封装是指隐藏对象的内部状态,并要求所有交互都通过方法进行。这样可以保护数据免受意外破坏,并允许内部实现更改而不影响程序的其他部分。在面向对象语言中,private 和 public 等访问修饰符控制可见性。
For Edexcel, you should know that attributes are usually declared private, while selected methods are public. Encapsulation is often tested by asking why direct access to attributes is harmful, or why getter and setter methods are used.
Inheritance allows a class (subclass) to reuse and extend the attributes and methods of another class (superclass). For example, a Car class can inherit from a Vehicle class. This promotes code reuse and models ‘is-a’ relationships. Edexcel exam questions often provide a class diagram and ask you to explain the relationship.
CLASS Car INHERITS Vehicle EXTRA ATTRIBUTE numberOfDoors OVERRIDE METHOD displayDetails() ENDCLASS
The subclass Car automatically has all the features of Vehicle, but can add new features or change existing ones. This is a high-yield exam topic, especially when combined with overriding.
子类 Car 自动拥有 Vehicle 的所有特征,但可以添加新特征或修改已有特征。这是一个高频率考点,特别是与重写结合时。
6. Polymorphism | 多态
Polymorphism means ‘many forms’. It allows the same method name to behave differently depending on the object that calls it. Method overriding is a common form: a subclass provides its own version of a method inherited from the superclass. In a list of Vehicle objects, calling vehicle.display() can produce different output for a Car, Bike or Lorry.
This is powerful because a single line of code can work with many types of object without knowing their exact class at compile time. Edexcel questions sometimes ask you to describe how polymorphism improves code maintainability.
7. Association, Aggregation and Composition | 关联、聚合与组合
These terms describe relationships between classes. Association is a general ‘uses-a’ relationship. Aggregation is a ‘has-a’ relationship where the contained object can exist independently, such as a Library having Books. Composition is a stronger ‘has-a’ relationship where the part cannot exist without the whole, such as a House having Rooms. Edexcel questions may ask you to distinguish these.
Useful exam wording: if the contained object is created and destroyed with the owner, it is composition; if it can outlive the owner, it is aggregation. Drawing clear class diagrams with labelled relationships earns marks even if the diagram is not perfect.
Advantages include improved modularity, code reuse through inheritance, easier maintenance due to encapsulation, and the ability to model real-world entities naturally. Disadvantages include a steeper learning curve, increased memory overhead, and the risk of overly complex class hierarchies. You should be prepared to evaluate OOP in a given context.
For high-mark questions, avoid simply listing advantages. Instead, link each point to the scenario: for example, encapsulation prevents invalid data in a banking system, while inheritance reduces duplication in a school records system.
9. Exam-Style Scenario: Modelling a School System | 考试情境:学校系统建模
Consider a school information system. You might define a Person class with attributes name and dateOfBirth, and method getAge(). Student inherits from Person and adds attributes studentID and tutorGroup; Teacher inherits from Person and adds staffID and subject. This demonstrates inheritance, encapsulation and polymorphism in a single scenario. An exam question could ask you to draw a class diagram or write pseudocode for one method.
考虑一个学校信息系统。你可以定义 Person 类,其属性为 name 和 dateOfBirth,方法为 getAge()。Student 继承自 Person,新增属性 studentID 和 tutorGroup;Teacher 继承自 Person,新增 staffID 和 subject。这在一个情境中演示了继承、封装和多态。考题可能要求你画出类图或为一个方法编写伪代码。
In such scenarios, always identify the superclass first, then decide what subclasses add. The ‘is-a’ test helps: a Student is a Person, so inheritance is valid. A Classroom is not a Person, so it should not inherit from Person; instead it may be associated with Person objects.
在这类情境中,始终先确定父类,再决定子类新增什么。“是一种”测试很有帮助:Student 是 Person,所以继承有效。Classroom 不是 Person,因此不应继承自 Person;相反,它可以与 Person 对象关联。
10. Common Pitfalls and Revision Tips | 常见误区与复习建议
A common mistake is confusing a class with an object: a class is the definition, an object is a specific instance. Another pitfall is treating inheritance as a ‘has-a’ relationship, when it should be ‘is-a’. Practise identifying attributes and methods from a passage, and be precise with access modifiers in exam answers. Use past paper scenarios to build speed.
When writing pseudocode, do not forget to declare the class, list its attributes, and show method signatures. Even if you cannot write perfect code, structured pseudocode with clear labels will earn method and attribute marks.
Understanding operators and programming structures is essential for success in the Edexcel A-Level Computer Science Paper 2 and the non-exam assessment. This article covers arithmetic, comparison and Boolean operators, precedence rules, and the three core control structures: sequence, selection and iteration.
理解运算符和程序结构对于在 Edexcel A-Level 计算机科学 Paper 2 及课程作业中取得成功至关重要。本文涵盖算术、比较和布尔运算符、优先级规则,以及三种核心控制结构:顺序、选择和迭代。
1. Arithmetic Operators and Precedence | 算术运算符与优先级
In Edexcel pseudocode, arithmetic operators include + addition, – subtraction, * multiplication, / division, DIV integer division, MOD remainder and ^ exponentiation. The result of DIV and MOD depends on whole-number operands.
Operators are evaluated in a strict order: brackets first, then ^, then * / DIV MOD, and finally + –. For example, 3 + 4 * 2 equals 11 because multiplication happens before addition.
Comparison operators compare two values and return a Boolean result. Edexcel pseudocode uses = for equality, <> for not equal, > for greater than, < for less than, >= for greater than or equal to, and <= for less than or equal to.
📚 Operators and Expressions in Programming | 编程中的运算符与表达式
Operators and expressions are fundamental to writing correct programs in any language. In Edexcel A-Level Computer Science, candidates must be able to use arithmetic, relational, Boolean and assignment operators confidently, and must understand how precedence rules determine the order of evaluation. This article explains each operator category with clear examples, common pitfalls, and exam-style tips.
Arithmetic operators perform mathematical calculations on numeric values. The standard operators include addition (+), subtraction (-), multiplication (*), division (/), integer division (// or DIV), modulo (%), and exponentiation (** or ^ depending on the language).
In Python, the expression 7 + 3 * 2 evaluates to 13 because multiplication has higher precedence than addition. The expression (7 + 3) * 2 evaluates to 20, showing how parentheses change the order of calculation.
This guide focuses on the programming skills required for Edexcel A-Level Computer Science. It covers data types, control flow, data structures, algorithms, recursion, object-oriented basics, file handling, testing and exam-style problem solving. Each section gives you the key idea in English followed by a Chinese explanation to support bilingual revision.
1. Computational Thinking and Program Design | 计算思维与程序设计
Before writing code, decompose the problem into smaller tasks, identify patterns, and generalise repeating steps into loops or functions. Use pseudocode or structured English to plan logic before coding.
In Edexcel exams, questions often ask you to trace or complete an algorithm, so a clear design reduces errors and saves time. The three key skills are abstraction, decomposition and pattern recognition.
Choose appropriate data types: integer for whole numbers, real/float for decimals, Boolean for TRUE/FALSE, character for single symbol, and string for text. Declare variables with meaningful names.
Type casting changes one data type into another, for example integer to string for output. Check that operations do not cause overflow or truncation errors, especially when dividing integers.
Constants should be used for fixed values like tax rate or pi, because they make code easier to update and prevent accidental changes.
常量应用于固定值,如税率或圆周率 pi,因为它们使代码更易于更新并防止意外修改。
3. Control Structures: Sequence, Selection, Iteration | 控制结构:顺序、选择与迭代
Sequence means statements run one after another. Selection uses IF, ELSE IF, ELSE, or CASE statements to choose between paths based on conditions.
顺序意味着语句一条接一条执行。选择使用 IF、ELSE IF、ELSE 或 CASE 语句根据条件在不同路径之间选择。
Iteration repeats a block of code. Definite iteration uses FOR loops when the number of repeats is known, while indefinite iteration uses WHILE or REPEAT UNTIL when it depends on a condition.
迭代重复执行一段代码。当重复次数已知时使用 FOR 循环进行确定迭代;当次数取决于条件时使用 WHILE 或 REPEAT UNTIL 进行不确定迭代。
Nested control structures can solve complex problems such as tables, matrices or searching grids, but keep indentation clear. In pseudocode, use consistent indentation to show the scope of each block.
4. Functions, Procedures and Parameters | 函数、过程与参数
A procedure performs a task without returning a value, while a function returns a value to the caller. Both help to split code into reusable modules.
过程执行任务但不返回值,函数将值返回给调用者。两者都有助于将代码拆分为可重用模块。
Parameters pass data into subroutines. Passing by value copies the argument, so changes do not affect the original; passing by reference allows the subroutine to change the original variable.
Use local variables inside subroutines to avoid side effects and global variables only when necessary. A function should normally have one clear purpose and a single return point.
5. Data Structures: Arrays and Records | 数据结构:数组与记录
A 1D array stores elements of the same data type in contiguous memory, accessed by index. A 2D array is useful for grids or tables.
一维数组在连续内存中存储相同数据类型的元素,通过索引访问。二维数组适用于网格或表格。
Records group related data of different types into one structure, for example a student record with name, id and score. In Python, dictionaries or classes can represent records; in pseudocode, use a RECORD … ENDRECORD block.
记录将不同类型但相关的数据组合成一个结构,例如包含姓名、编号和成绩的学生记录。在 Python 中可以用字典或类表示记录;在伪代码中使用 RECORD … ENDRECORD 块。
Stacks use Last In First Out (LIFO) and queues use First In First Out (FIFO). These are common abstract data types tested in Edexcel programming questions, often with push, pop, enqueue and dequeue operations.
Linear search checks each element until the target is found; it works on unsorted data and has average time complexity O(n). Binary search repeatedly halves a sorted list, giving O(log n).
Bubble sort passes through adjacent pairs to swap out-of-order elements; insertion sort builds a sorted part by inserting each next element; merge sort divides and merges. Use trace tables to show each pass.
A recursive routine calls itself with a smaller input. It must have a base case to stop and a recursive case that moves toward the base case.
递归例程用更小的输入调用自身。它必须有停止的基本情形,以及向基本情形推进的递归情形。
Example: factorial(n) = n × factorial(n − 1), with factorial(0) = 1. Trace trees show each call and return value, helping you avoid missing the base case.
示例:factorial(n) = n × factorial(n − 1),且 factorial(0) = 1。追踪树展示每次调用和返回值,帮助你避免遗漏基本情形。
Recursion uses the call stack, so too many calls can cause stack overflow; iterative solutions are often more memory-efficient. In Edexcel pseudocode, recursive functions are written like normal functions but contain a call to themselves.
A class is a blueprint; an object is an instance. Attributes store data and methods define behaviour. Encapsulation hides internal details and exposes only a public interface.
类是蓝图;对象是实例。属性存储数据,方法定义行为。封装隐藏内部细节,只暴露公共接口。
Inheritance allows a subclass to reuse and extend a parent class. Polymorphism lets different objects respond to the same method call in their own way.
继承允许子类复用并扩展父类。多态让不同对象以各自的方式响应同一方法调用。
In Edexcel A-Level, OOP questions usually ask you to identify classes, attributes, methods and relationships, not to write full class syntax. However, you should know the terms constructor, getter and setter.
Common file operations are open, read, write, append and close. Always close files to free system resources.
常见文件操作包括打开、读取、写入、追加和关闭。始终关闭文件以释放系统资源。
Validation checks input before processing: presence, range, type, length and format. Verification such as double entry checks that data is entered correctly.
验证在处理前检查输入:存在性、范围、类型、长度和格式。核实如双重输入用于检查数据输入正确。
Use exception handling to manage file not found, wrong type or end-of-file conditions without crashing. In pseudocode, this can be shown with TRY … EXCEPT or OPEN FILE … IF NOT EXISTS.
使用异常处理来管理文件不存在、类型错误或文件结束等情况而不崩溃。在伪代码中,可以用 TRY … EXCEPT 或 OPEN FILE … IF NOT EXISTS 表示。
10. Testing, Debugging and Exam Technique | 测试、调试与应试技巧
Create a test plan with normal, boundary and erroneous data. For example, if a mark must be 0–100, test 50, 0, 100, −1 and 101.
Dry run algorithms with trace tables tracking variables and outputs step by step. This is a key Edexcel exam skill because many questions ask you to complete a trace table or identify the final output.
Read questions carefully: if asked to write an algorithm, use clear pseudocode; if asked to identify errors, compare the code with the required logic. Check that your solution handles all valid inputs and at least one invalid input.
📚 Operators, Expressions and Precedence in Programming | 编程中的运算符、表达式与优先级
In Edexcel A-Level Computer Science, understanding operators and how expressions are evaluated is essential for writing correct pseudocode and for tracing algorithms. This article covers the operators you need to know, their precedence, and common exam-style pitfalls.
Operators are special symbols or keywords that tell the computer to perform a specific operation on one or more values. In A-Level programming, you must be able to use arithmetic, relational, Boolean, string, and assignment operators in pseudocode and in a chosen high-level language.
Assignment operators – store values. | 赋值运算符 – 存储值。
Understanding how these operators interact in an expression is a core skill for tracing and writing algorithms.
理解这些运算符在表达式中如何相互作用,是追踪和编写算法的核心技能。
2. Arithmetic Operators | 算术运算符
Arithmetic operators are used for mathematical calculations. In Edexcel pseudocode, the usual symbols are +, -, *, /, DIV and MOD. DIV returns the whole-number quotient, while MOD returns the remainder after whole-number division.
算术运算符用于数学计算。在 Edexcel 伪代码中,常用符号是 +、-、*、/、DIV 和 MOD。DIV 返回整数商,而 MOD 返回整数除法后的余数。
Operator
Meaning
Example
Result
+
Addition 加
7 + 2
9
–
Subtraction 减
7 – 2
5
*
Multiplication 乘
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com
Object-oriented programming (OOP) is a central paradigm in the Edexcel A-Level Programming specification. It models real-world entities as objects that combine data and behaviour. This article covers the key OOP concepts you must understand for the exam, including classes, objects, encapsulation, inheritance and polymorphism.
1. What is Object-Oriented Programming? | 什么是面向对象编程?
Object-oriented programming is a programming paradigm based on the concept of objects. Each object contains data, known as attributes, and code, known as methods. The main aim is to structure programs so that they are easier to design, debug and maintain.
In Edexcel A-Level exams, you may be asked to explain why OOP is suitable for large software projects. Key reasons include modularity, reusability and the ability to hide internal details from other parts of the program.
Example: A ‘BankAccount’ object can hold a balance attribute and methods such as deposit() and withdraw(). This keeps related data and operations together.
A class is a template or blueprint that defines the attributes and methods common to a group of objects. An object is a specific instance of a class created at runtime. The distinction between class and object is frequently examined.
In Python, you define a class using the ‘class’ keyword. Creating an object uses the class name followed by parentheses. The following code shows a simple Dog class and two Dog objects.
在 Python 中,使用 ‘class’ 关键字定义类。创建对象时使用类名后跟括号。以下代码展示了一个简单的 Dog 类和两个 Dog 对象。
class Dog: def __init__(self, name): self.name = name
dog1 = Dog(‘Rex’) dog2 = Dog(‘Bella’)
Here ‘Dog’ is the class and ‘dog1’ and ‘dog2’ are objects or instances of the class. Each object has its own copy of the ‘name’ attribute.
Attributes are variables that belong to an object and store its state. Methods are functions defined inside a class that describe the behaviours of the object. In exam questions, you must be able to identify attributes and methods from class diagrams or code.
For example, a Student class may have attributes such as name, age and grade, and methods such as enrol() and calculateAverage(). Methods often use the ‘self’ parameter in Python to refer to the current object.
Attributes can be public or private. Private attributes are indicated by a double underscore prefix in Python, but the concept of visibility is more important than syntax in Edexcel exams.
属性可以是公有或私有。在 Python 中,
Published by TutorHao | A-Level 编程 Revision Series | aleveler.com