Skip to content · ⁨الانتقال إلى المحتوى⁩

Further Programming · ⁨البرمجة المتقدمة⁩

A-Level Computer Science · ⁨A-Level علوم الحاسوب⁩ · Topic 20 · ⁨الموضوع 20⁩

Video lesson for this topic · ⁨درس فيديو لهذا الموضوع⁩ Open the video page · ⁨افتح صفحة الفيديو⁩
13:52

نماذج البرمجة

إليك مهمة واحدة: سرد كل طالب حصل على درجة A. يكتب مبرمج حلقة تكرار — ابدأ من السجل الأول، تحقق من الدرجة، أضف الاسم إلى قائمة، انتقل…

English narration · English + 中文 subtitles burned in · ⁨سرد باللغة الإنجليزية · ترجمة مدمجة بالإنجليزية + الصينية⁩

20.1

Programming paradigms · ⁨نماذج البرمجة⁩

Syllabus · ⁨المنهج⁩
English
Candidates should be able to: Notes and guidance
Understanding what is meant by a programming paradigm
Show understanding of the characteristics of a number of programming paradigms:
• Low-level Low-level Programming: • understanding of and ability to write low-level code that uses various addressing modes: immediate, direct, indirect, indexed and relative
• Imperative (Procedural) Imperative (Procedural) programming: • Assumed knowledge and understanding of Structural Programming (see details in AS content section 11.3) • understanding of and ability to write imperative (procedural) programming code that uses variables, constructs, procedures and functions. See details in AS content
• Object Oriented Object-Oriented Programming (OOP): • understanding of the terminology associated with OOP (including objects, properties/attributes, methods, classes, inheritance, polymorphism, containment (aggregation), encapsulation, getters, setters, instances) • understanding of how to solve a problem by designing appropriate classes • understanding of and ability to write code that demonstrates the use of OOP
• Declarative Declarative programming: • understanding of and ability to solve a problem by writing appropriate facts and rules based on supplied information • understanding of and ability to write code that can satisfy a goal using facts and rules
العربية
يجب أن يكون المرشحون قادرين على: ملاحظات وإرشادات
فهم ما يعنيه بارادايم البرمجة
إظهار فهم خصائص عدد من بارادايم البرمجة:
• منخفض المستوى البرمجة منخفضة المستوى: • فهم وقدرة على كتابة كود منخفض المستوى يستخدم مختلف أنماط العنونة: الفوري، المباشر، غير المباشر، المؤشر والنسبي
• أمرية (إجراءية) البرمجة الأمرية (الإجراءية): • معرفة وفهم البرمجة الهيكلية (انظر التفاصيل في قسم محتوى AS 11.3) • الفهم والقدرة على كتابة أكواد برمجية أمرية (إجراءية) تستخدم المتغيرات، والتراكيب، والإجراءات، والدوال. انظر التفاصيل في محتوى AS
• كائنية التوجه البرمجة كائنية التوجه (OOP): • فهم المصطلحات المرتبطة بـ OOP (بما في ذلك الكائنات، الخصائص/السمات، الطرق، الفئات، الوراثة، تعدد الأشكال، التضمين (التجميع)، التغليف، المستحقات، المنسِّطات، الحالات) • فهم كيفية حل مشكلة من خلال تصميم فئات مناسبة • الفهم والقدرة على كتابة كود يوضح استخدام البرمجة كائنية التوجه
• إعلانية البرمجة الإعلانية: • الفهم والقدرة على حل مشكلة من خلال كتابة حقائق وقواعد مناسبة بناءً على المعلومات المقدمة • الفهم والقدرة على كتابة كود يمكنه تحقيق هدف باستخدام الحقائق والقواعد

Source: Cambridge International syllabus · ⁨المصدر: منهج كامبريدج الدولي⁩

English

A programming paradigm 编程范式 is a style of programming — a way of structuring programs, with its own ideas and language features. Four programming paradigms are in this syllabus.

"Describe what is meant by an imperative (procedural) language" (two marks). A language in which the program is a sequence of instructions that are executed in order and that change the program's state; the programmer says how the task is done, using procedures, sequence, selection and iteration. "Describe what is meant by a declarative language": the program states facts and rules (what is known and what is wanted) and the language's inference engine works out how to find the answer; the programmer does not give the sequence of steps.

Identify the paradigm from a code sample (a regular Paper 3 question): LDD 200, ADD #5, STO 201 is low-level (mnemonics, registers, memory addresses); FOR Count ← 1 TO 10 … NEXT Count with procedures and assignments is imperative; CLASS Dog … PRIVATE Name : STRING … PUBLIC PROCEDURE NEW(…) is object-oriented; type(lion, wild). and dangerous(X) IF type(X, wild) is declarative (logic). In the matching question: low-level pairs with "mnemonics that correspond directly to machine instructions", imperative with "a sequence of statements that change the state", OOP with "objects that combine attributes and methods", declarative with "facts and rules, with no order of execution given".

Low-level programming

Programming close to the hardware in machine code 机器码 or assembly language 汇编语言, where each instruction maps to what the CPU runs. It gives direct access to registers 寄存器 and memory addresses 内存地址, using different addressing modes 寻址方式 (immediate, direct, indirect, indexed and relative). It is very fast and compact, but architecture-specific, tedious, and hard to maintain. This is low-level 低级 programming, used for device drivers, firmware and bootloaders.

The five addressing modes. The syllabus asks for low-level code that uses each addressing mode (the instruction set is in Topic 4). The operand of a load instruction can be read five ways, and the exam gives you the memory contents and asks what the accumulator holds:

  • immediate (LDM #105): the operand is the value; ACC becomes 105.
  • direct (LDD 105): the operand is the address of the value; ACC becomes the contents of 105, here 27.
  • indirect (LDI 105): the operand is the address of an address; ACC becomes the contents of 27, here 91. Used for pointers and for data whose position is decided at run time.
  • indexed (LDX 105): the address is the operand plus the index register IX; with IX = 2, ACC becomes the contents of 107. Used to step through an array by incrementing IX.
  • relative (JMR +65): the target is an offset from the address of the current instruction, which makes the code relocatable.

Worked example. Memory: 105 holds 27, 106 holds 64, 200 holds 0. Write code to add the contents of 105 and 106, store the result in 200 and output it. LDD 105 (ACC = 27), ADD 106 (ACC = 91), STO 200, OUT. To double the value in 105 instead: LDD 105, ADD 105, STO 105. State the register contents after each line when asked to trace.

Imperative (procedural) programming

In imperative programming 命令式编程 the programmer writes a sequence of commands that change the program's state — assignments, conditionals, loops, function calls. Variables 变量 hold state; statements change it; code is organised into procedures and functions (also called structured or structural programming). This is the style of Topics 9 and 11 (Python, C). Strong when the algorithm has clear sequential steps.

Object-oriented programming (OOP)

In object-oriented programming 面向对象编程 programs are built from objects 对象 — units combining data (attributes 属性) and operations (methods 方法). Objects are instances 实例 of classes 类. The four pillars:

  • encapsulation 封装 — an object's data is hidden behind its methods; outside code uses the public methods only, not the data directly. This protects the object and lets its internals change without breaking callers. For example, a BankAccount hides its balance; you change it only through deposit() and withdraw(), which can enforce a rule like "never go below zero".
  • inheritance 继承 — a subclass 子类 specialises a superclass 父类, inheriting its attributes and methods and adding or overriding 重写 them. Models "is-a" ("a Manager is an Employee").
  • polymorphism 多态 — different objects respond to the same method call differently; the caller need not know the exact type. Every Shape has Area(), and a Circle and a Rectangle each implement it their own way.
  • abstraction 抽象 — show a simple interface and hide the implementation.

Other terms:

  • a constructor 构造函数 is a special method run when an object is created, to set up its attributes.
  • getters and setters read and write an object's attributes (its properties) through methods.
  • aggregation 聚合 and containment 包含 build an object from other objects (a "has-a" relationship).

OOP is used for large systems, GUIs, simulations and games.

OOP as the examiner marks it

Definitions. Class: a template (blueprint) that defines the attributes and methods of the objects of that type. Object: an instance of a class, created from it, with its own values for the attributes ("an occurrence of an object" is the exam's phrase for an instance). Attribute (property): a data item belonging to a class. Method: a procedure or function belonging to a class that acts on its attributes. Encapsulation: combining the attributes and methods in one class and restricting external access to the data: the attributes are private and can only be read or changed through public methods. Inheritance: a subclass acquires the attributes and methods of its parent (super) class and can add its own or override them. Polymorphism: methods with the same name that behave differently in different classes; typically a subclass redefines a method of its parent, and the right version runs for each object. Containment: a class has an object of another class as an attribute (a car has an engine). "Identify the feature that restricts external access to the data" is encapsulation; "the term for an occurrence of an object" is instance.

"Outline the structure of a class" (three marks): attributes (properties) that hold the object's data, usually declared private; methods (procedures and functions) that act on those attributes, usually public; and a constructor, a method that runs when an object is created to initialise the attributes. "Give three benefits of OOP": code is reused through inheritance; data is protected by encapsulation, so it can only be changed by the class's own methods; a large program is split into classes that are written and tested independently, so it is easier to maintain and extend; classes model real-world entities, so the design is easier to understand; polymorphism lets the same call work for different objects.

The class in pseudocode, as Paper 3 sets it:

An object is created with MyCar ← NEW Car("AB12 CDE", 2020) and used with MyCar.AddMileage(150) and OUTPUT MyCar.GetMileage(). A subclass reuses the parent's constructor through SUPER:

The same class in Python, as Paper 4 expects it: attributes are made private with a double underscore, the constructor is __init__, and a subclass names its parent in brackets and calls super().__init__(…):

In Java the same ideas are private/public fields, a constructor with the class's name, extends and super(…); in VB.NET Private/Public, Sub New, Inherits and MyBase.New. A polymorphic method is written in the parent and overridden in the child with the same name; a call through a parent-type variable runs the child's version.

Data structures as objects. Paper 4 builds a stack, linked list or binary tree from a Node class whose attributes are the data and one or two references to other nodes; a Tree (or LinkedList) class holds the root (or start) and the methods.

A find method walks the same path and returns TRUE when Current.Data = Target, FALSE when it reaches NULL; an in-order output method is recursive: output the left subtree, the node, then the right subtree. For a linked list the node has one reference, Next, and the list class holds Start; for a stack built from a list, push and pop both work at Start.

Worked example. A game has characters. Each has a name, health (starting at 100) and a position given by X and Y. Write a class Character with a constructor and a method Move(DX, DY); then a subclass Wizard that adds Mana (starting at 50) and a method CastSpell() that takes 10 mana and returns TRUE if there was enough.

The marks are for private attributes, a constructor that sets every attribute, the inheritance line, the call to the parent's constructor, and a method that uses and changes the object's own data. When the question asks for a class diagram, draw a box in three parts (name; attributes with - for private; methods with + for public) and join a subclass to its parent with an arrow pointing at the parent.

Declarative programming

In declarative programming 声明式编程 you say what to compute, not how — the runtime works out the steps. Two kinds:

  • functional programming 函数式编程 — built from pure functions 纯函数 (no side effects 副作用; same input always gives the same output) composed together. Examples: Haskell, Lisp.
  • logic programming 逻辑编程 — state facts and rules; the engine answers a goal (query) by inference. Example: Prolog.

A familiar declarative example is SQL 结构化查询语言: SELECT * FROM Customer WHERE Country = 'UK' says what you want, not how to walk the records.

Facts, rules and goals are what the exam tests in the declarative paradigm. Given these facts 事实 (statements that are true) and a rule 规则 (a conclusion that holds when its conditions hold):

"Write the result of the goal type(X, wild)": X = leopard, X = lion. The engine matches the goal against each fact in turn; every match is a solution, and a capital letter is a variable that the match fills in. "Write a fact to show that a cheetah is wild": type(cheetah, wild). "Explain what line 07 does": it defines a rule with the conclusion dangerous(X), which is true for any X that is both wild and large, so dangerous(A) returns A = leopard, A = lion. "Write a rule: a feature F may be available for a body style B if F is a feature and B is a body style and F is not unavailable for B": may_be_available(F, B) IF feature(F) AND body_style(B) AND NOT unavailable(F, B). Copy the exact predicate names and argument order used in the question's facts; a new fact ends with a full stop, and a rule's conditions are joined with AND.

Comparing paradigms

Paradigm Strength Typical languages
Low-level maximum control, speed assembly
Imperative direct, intuitive C, Python
Object-oriented modular, models entities Java, C#, Python
Functional clear, no side effects Haskell, F#
Logic inference, rules Prolog
Database data queries SQL

Modern languages often mix paradigms — Python supports all of procedural, OOP and functional. The right one depends on the problem.

العربية

نموذج برمجي هو أسلوب في البرمجة — طريقة لهيكلة البرامج، مع أفكار وميزات لغوية خاصة به. يوجد أربعة نماذج برمجية في هذا المنهج الدراسي.

"وصف ما يُقصَد بلغة أمرية (إجراءية) (درجتان). لغة يكون فيها البرنامج متتالية من التعليمات تُنفَّذ بالتتابع وتُغيِّر حالة البرنامج؛ حيث يحدد المبرمج كيف يتم إنجاز المهمة، باستخدام الإجراءات، والتتبع، والاختيار، والتكرار. "وصف ما يُقصَد بلغة إعلانية": يُعرِّف البرنامج حقائق وقواعد (ما هو معلوم وما هو مطلوب)، ويعمل محرك الاستنتاج الخاص باللغة على تحديد كيفية إيجاد الإجابة؛ ولا يقدم المبرمج تسلسل الخطوات.

تحديد النموذج البرمجي من عينة كود (سؤال نموذجي لورقة 3): LDD 200، ADD #5، STO 201 هي منخفضة المستوى (أسماء رمزية، مسجلات، عناوين ذاكرة)؛ FOR Count ← 1 TO 10 … NEXT Count مع الإجراءات والتعيينات هو أمري؛ CLASS Dog … PRIVATE Name : STRING … PUBLIC PROCEDURE NEW(…) هو كائني التوجه؛ type(lion, wild). وdangerous(X) IF type(X, wild) هما إعلانيان (منطق). في سؤال المطابقة: ترتبط منخفضة المستوى بـ "أسماء رمزية تقابل تعليمات الآلة مباشرةً"، والأمرية بـ "متتالية من العبارات التي تُغيِّر الحالة"، وكائني التوجه بـ "كائنات تجمع بين الخصائص والطرق"، والإعلاقي بـ "حقائق وقواعد بدون تحديد ترتيب تنفيذها".

أربعة نماذج: منخفضة المستوى، وأمرية، وكائنية التوجه، وإعلانية
أربعة نماذج: منخفضة المستوى، وأمرية، وكائنية التوجه، وإعلانية

البرمجة منخفضة المستوى

البرمجة القريبة من الأجهزة في كود الآلة أو لغة التجميع، حيث يرتبط كل تعليمة بما تنفذه وحدة المعالجة المركزية. توفر وصولاً مباشراً إلى المسجلات وعناوين الذاكرة، باستخدام أنماط عنوان مختلفة (الفوري المباشر، المباشر، غير المباشر، الفهرسي والنسبي). وهي سريعة جداً وصغيرة الحجم، لكنها محددة بمعمارية معينة، ومتعبة، وصعبة الصيانة. هذه هي البرمجة منخفضة المستوى، المستخدمة في تعريفات الأجهزة، والبرامج الثابتة، وبرامج الإقلاع.

أنماط العنوان الخمسة. يطلب المنهج كوداً منخفض المستوى يستخدم كل نمط عنوان (مجموعة التعليمات موجودة في الموضوع 4). يمكن قراءة مُعامل تعليمة التحميل بخمس طرق، وتعطيك الامتحان محتويات الذاكرة وتطلب معرفة ما يحتويه المسجل المُجمِّع:

جدول ذاكرة بعناوين 105، 106، 107، 27 و145 ومحتوياتها، بجانب خمسة صفوف توضح ما يستقبله المسجل المُجمِّع من LDM #105، LDD 105، LDI 105، LDX 105 مع IX = 2، القفز النسبي
نفس المُعامل، 105، يُقرأ خمس طرق: كقيمة، وعنوان، وعنوان لعنوان، وعنوان زائد المسجل الفهرسي، وإزاحة من التعليمة الحالية
  • فوري (LDM #105): المُعامل هو القيمة؛ يصبح المسجل المُجمِّع 105.
  • مباشر (LDD 105): المُعامل هو عنوان القيمة؛ يصبح المسجل المُجمِّع محتوى 105، وهو هنا 27.
  • غير مباشر (LDI 105): المُعامل هو عنوان لعنوان؛ يصبح المسجل المُجمِّع محتوى 27، وهو هنا 91. يُستخدم للؤاسيس ولبيانات يكون موقعها محددًا وقت التشغيل.
  • فهرسي (LDX 105): العنوان هو المُعامل زائد المسجل الفهرسي IX؛ مع IX = 2، يصبح المسجل المُجمِّع محتوى 107. يُستخدم للمرور عبر مصفوفة عن طريق زيادة IX.
  • نسبي (JMR +65): الهدف هو إزاحة من عنوان التعليمة الحالية، مما يجعل الكود قابلاً للانتقال.

مثال محلّل. الذاكرة: 105 يحتوي على 27، 106 يحتوي على 64، 200 يحتوي على 0. اكتب كوداً لإضافة محتويات 105 و106، وتخزين النتيجة في 200، وطباعتها. LDD 105 (ACC = 27)، ADD 106 (ACC = 91)، STO 200، OUT. لتضعف القيمة في 105 بدلاً من ذلك: LDD 105، ADD 105، STO 105. حدد محتويات المسجلات بعد كل سطر عند طلب التتبع.

البرمجة الأمرية (الإجراءية)

في البرمجة الأمرية يكتب المبرمج متتالية من الأوامر التي تُغيِّر حالة البرنامج — التعيينات، والشروط، والحلقات، واستدعاء الدوال. تحتفظ المتغيرات بالحالة؛ وتُغيِّر العبارات حالتها؛ وينظم الكود في إجراءات ودوال (تُسمى أيضاً البرمجة المهيكلة أو البنائية). هذا هو أسلوب الموضوعين 9 و11 (Python، C). قوية عندما يكون خوارزمية ذات خطوات متتالية واضحة.

البرمجة كائنية التوجه (OOP)

في البرمجة كائنية التوجه تُبنى البرامج من كائنات — وحدات تجمع بين البيانات (الخصائص) والعمليات (الطرق). الكائنات هي أمثلة على فئات. الأعمدة الأربعة:

  • التغليف — بيانات الكائن مخفية خلف طرقها؛ يستخدم الكود الخارجي الطرق العامة فقط، لا البيانات مباشرة. هذا يحمي الكائن ويسمح بتغيير internals دون كسر المتصلين. على سبيل المثال، يخفي BankAccount balance؛ تقوم بتغييره فقط عبر deposit() وwithdraw()، والتي يمكنها فرض قاعدة مثل "لا تتجاوز الصفر".
  • الوراثة — تخصص فئة فرعية فئة أم، ترث خصائصها وطرقها وتضيف أو تستبدل بعضها. نمذج "هو-أ" ("المدير هو موظف").
  • تعدد الأشكال — تستجيب كائنات مختلفة لـ نفس استدعاء الطريقة بشكل مختلف؛ لا يحتاج المتصل إلى معرفة النوع الدقيق. كل Shape لديه Area()، ويُنفِّذ Circle وRectangle كل منهما طريقتهم الخاصة.
  • التجريد — عرض واجهة بسيطة وإخفاء التنفيذ.

مصطلحات أخرى:

  • المنشئ هو طريقة خاصة تُنفَّذ عند إنشاء كائن، لإعداد خصائصه.
  • الحاصِلات والعَمِّلات تقرأ وتكتب خصائص الكائن (خصائصه) عبر الطرق.
  • التجميع والاحتواء يبنيان كائنًا من كائنات أخرى (علاقة "يحتوي على").

تُستخدم البرمجة كائنية التوجه للأنظمة الكبيرة، والواجهات الرسومية، والمحاكاة، والألعاب.

نفس شكل الاستدعاء.Area() ينفذ أكوادًا مختلفة لكل كائن: الدائرة تحسب باي × ر²، والمستطيل يحسب العرض × الارتفاع
تعدد الأشكال: نفس استدعاء الطريقة ينفذ كود كل كائن خاصًا به
رسم تخطيط فئات UML لشكل الشكل: صندوق ثلاثي الأجزاء مع اسم الفئة، والخصائص الخاصة (الاسم، المساحة، المحيط، محددة بعلامة ناقص) والطرق العامة (ضبطالشكل، حسابالمساحة، حسابالمحيط، محددة بعلامة زائد)
رسم تخطيط لفئة الشكل: خصائص خاصة وطرق عامة
رسم توريث UML: فئة الموظف الأب في الأعلى، مع فئات جزئي الوقت وكامل الوقت أدناه، متصلة بكل منها بالأب بسهم تعميم مثلث فارغ وتضيف خصائصها وطرقها الخاصة
التوريث: جزئي الوقت وكامل الوقت هما فروع فرعية للموظف
كائن حساب بنكي برصيد خاص لا يمكن الوصول إليه إلا عبر الطرق العامة إيداع() وسحب(); لا يمكن للكود الخارجي لمس البيانات مباشرة
التغليف: بيانات الكائن خاصة، ولا يمكن الوصول إليها إلا عبر طرقه العامة

البرمجة كائنية التوجه كما يقيّمها الممتحن

التعريفات. الفئة: قالب (مخطط هندسي) يُعرّف الخصائص والطرق الخاصة بكائنات ذلك النوع. الكائن: مثال من فئة، يتم إنشاؤها منه، ويملك قيمًا خاصة بها للخصائص (عبارة "حدوث لكائن" هي مصطلح الامتحان للمثال). الخاصية: عنصر بيانات تابع لفئة. الطريقة: إجراء أو دالة تابعة لفئة تعمل على خصائصها. التغليف: دمج الخصائص والطرق في فئة واحدة وتقييد الوصول الخارجي إلى البيانات: الخصائص خاصة ويمكن قراءتها أو تغييرها فقط عبر طرق عامة. التوريث: تستحوذ الفرع الفرعي على خصائص وطرق الأب (الأعلى) ويمكنه إضافة خاصة بها أو استبدالها. تعدد الأشكال: طرق تحمل اسمًا相同ًا تتصرف بشكل مختلف في فئات مختلفة؛ عادةً ما يعيد الفرع الفرعي تعريف طريقة الأب، وتنسخ النسخة الصحيحة لكل كائن. الاحتواء: تمتلك الفئة كائنًا من فئة أخرى كخاصية (سيارة تحتوي على محرك). "تحديد السمة التي تقيد الوصول الخارجي إلى البيانات" هو التغليف؛ "المصطلح لحدوث لكائن" هو مثال.

"أشرح بنية الفئة" (ثلاث درجات): الخصائص (الصفات) التي تحتفظ ببيانات الكائن، تُعلن عادةً خاصة؛ الطرق (الإجراءات والدوال) التي تعمل على تلك الخصائص، عادةً ما تكون عامة؛ والمنشئ، وهو طريقة تنفذ عند إنشاء كائن لتهيئة الخصائص. "اذكر ثلاثة فوائد للبرمجة كائنية التوجه": الكود يُعاد استخدامه عبر التوريث؛ البيانات محمية بالتغليف، لذا لا يمكن تغييرها إلا بطرق الفئة الخاصة؛ البرنامج الكبير مقسم إلى فئات تُكتب وتُختبر بشكل مستقل، مما يسهل صيانتها وتطويرها؛ الفئات تحاكي كيانات عالمية حقيقية، مما يجعل التصميم أسهل للفهم؛ متعدد الأشكال يسمح بنفس الاستدعاء أن يعمل مع كائنات مختلفة.

الفئة في الكود الوهمي، كما يحدد امتحان الورقة 3:

CLASS Car
    PRIVATE Registration : STRING
    PRIVATE Year : INTEGER
    PRIVATE Mileage : INTEGER
    PUBLIC PROCEDURE NEW(NewReg : STRING, NewYear : INTEGER)
        Registration ← NewReg
        Year ← NewYear
        Mileage ← 0
    ENDPROCEDURE
    PUBLIC FUNCTION GetMileage() RETURNS INTEGER
        RETURN Mileage
    ENDFUNCTION
    PUBLIC PROCEDURE AddMileage(Extra : INTEGER)
        Mileage ← Mileage + Extra
    ENDPROCEDURE
ENDCLASS

يتم إنشاء كائن باستخدام MyCar ← NEW Car("AB12 CDE", 2020) واستخدامه مع MyCar.AddMileage(150) وOUTPUT MyCar.GetMileage(). يعيد الفرع الفرعي استخدام منشئ الأب عبر SUPER:

CLASS ElectricCar INHERITS Car
    PRIVATE BatteryCapacity : REAL
    PUBLIC PROCEDURE NEW(NewReg : STRING, NewYear : INTEGER, NewCapacity : REAL)
        SUPER.NEW(NewReg, NewYear)
        BatteryCapacity ← NewCapacity
    ENDPROCEDURE
ENDCLASS

نفس الفئة بلغة بايثون، كما تتوقعها الورقة 4: تُجعل الخصائص خاصة باستخدام شريطين سفليين، والمنشئ هو __init__، واسم الفرع الفرعي للأب بين أقواس واستدعاء super().__init__(…):

class Car:
    def __init__(self, reg, year):
        self.__registration = reg
        self.__year = year
        self.__mileage = 0
    def get_mileage(self):
        return self.__mileage
    def add_mileage(self, extra):
        self.__mileage = self.__mileage + extra

class ElectricCar(Car):
    def __init__(self, reg, year, capacity):
        super().__init__(reg, year)
        self.__capacity = capacity

cars = []
cars.append(Car("AB12 CDE", 2020))
cars.append(ElectricCar("EV21 XYZ", 2023, 75.0))
cars[1].add_mileage(150)
print(cars[1].get_mileage())

في جافا، هذه الأفكار هي private/public حقول، ومنشئ يحمل اسم الفئة، extends وsuper(…)؛ في VB.NET Private/Public، Sub New، Inherits وMyBase.New. تُكتب الطريقة متعددة الأشكال في الأب وتُستبدل في الابن بنفس الاسم؛ الاستدعاء عبر متغير من نوع الأب يشغل نسخة الابن.

الهياكل ككائنات. تبني الورقة 4 مكدسًا أو قائمة مرتبطة أو شجرة ثنائية من فئة Node خصائصها هي البيانات وإشارة أو اثنتين عقدتين أخريين؛ فئة Tree (أو LinkedList) تحتفظ بالجذر (أو البداية) والطرق.

شجرة ثنائية من كائنات العقدة: الجذر الخاص بكائن الشجرة يشير إلى العقدة 15، والتي تشير إشارتا اليسار واليمين إلى العقدتين 8 و19، وهكذا، مع None للإشارات الفارغة
شجرة ثنائية مبنية من الكائنات: كل عقدة تحتوي على بيانات بالإضافة إلى إشارتي يسار ويمين، والشجرة تحتفظ بالجذر؛ الإدراج يتبع الإشارات
CLASS Node
    PUBLIC Data : INTEGER
    PUBLIC Left : Node          // NULL when there is no child
    PUBLIC Right : Node
    PUBLIC PROCEDURE NEW(NewData : INTEGER)
        Data ← NewData
        Left ← NULL
        Right ← NULL
    ENDPROCEDURE
ENDCLASS

CLASS Tree
    PRIVATE Root : Node
    PUBLIC PROCEDURE Insert(NewData : INTEGER)
        DECLARE NewNode, Current : Node
        DECLARE Placed : BOOLEAN
        NewNode ← NEW Node(NewData)
        IF Root = NULL THEN
            Root ← NewNode
        ELSE
            Current ← Root
            Placed ← FALSE
            WHILE NOT Placed
                IF NewData < Current.Data THEN
                    IF Current.Left = NULL THEN
                        Current.Left ← NewNode
                        Placed ← TRUE
                    ELSE
                        Current ← Current.Left
                    ENDIF
                ELSE
                    IF Current.Right = NULL THEN
                        Current.Right ← NewNode
                        Placed ← TRUE
                    ELSE
                        Current ← Current.Right
                    ENDIF
                ENDIF
            ENDWHILE
        ENDIF
    ENDPROCEDURE
ENDCLASS

طريقة البحث تتبع نفس المسار وتعيد TRUE عندما Current.Data = Target، FALSE عندما تصل إلى NULL؛ طريقة العرض بالترتيب الإنجزي هي عودية: اعرض الفرع الأيسر، ثم العقدة، ثم الفرع الأيمن. بالنسبة للقائمة المرتبطة، للعقدة إشارة واحدة، Next، والفئة تحتفظ بـ Start؛ بالنسبة للمكدس المبني من قائمة، كلا العمليتين الدفع والسحب يعملان في Start.

مثال محلول. لعبة تحتوي على شخصيات. لكل منها اسم وصحة (تبدأ عند 100) وموضع معطى بواسطة X وY. اكتب فئة Character بمُشكّل وطريقة Move(DX, DY)؛ ثم فئة فرعية Wizard تضيف Mana (تبدأ عند 50) وطريقة CastSpell() تأخذ 10 طاقة وتعيد TRUE إذا كان هناك ما يكفي.

CLASS Character
    PRIVATE Name : STRING
    PRIVATE Health : INTEGER
    PRIVATE X : INTEGER
    PRIVATE Y : INTEGER
    PUBLIC PROCEDURE NEW(NewName : STRING, StartX : INTEGER, StartY : INTEGER)
        Name ← NewName
        Health ← 100
        X ← StartX
        Y ← StartY
    ENDPROCEDURE
    PUBLIC PROCEDURE Move(DX : INTEGER, DY : INTEGER)
        X ← X + DX
        Y ← Y + DY
    ENDPROCEDURE
ENDCLASS

CLASS Wizard INHERITS Character
    PRIVATE Mana : INTEGER
    PUBLIC PROCEDURE NEW(NewName : STRING, StartX : INTEGER, StartY : INTEGER)
        SUPER.NEW(NewName, StartX, StartY)
        Mana ← 50
    ENDPROCEDURE
    PUBLIC FUNCTION CastSpell() RETURNS BOOLEAN
        IF Mana >= 10 THEN
            Mana ← Mana - 10
            RETURN TRUE
        ELSE
            RETURN FALSE
        ENDIF
    ENDFUNCTION
ENDCLASS

الدرجات للخصائص الخاصة، ومنشئ يحدد كل خاصية، خط التوريث، استدعاء منشئ الأب، وطريقة تستخدم وتغير بيانات الكائن الخاصة. عندما يطلب السؤال رسم تخطيط للفئة، ارسم صندوقًا بثلاثة أجزاء (الاسم؛ الخصائص مع - للخاصة؛ الطرق مع + للعامة) وصل الفرع الفرعي بأباه بسهم يشير إلى الأب.

البرمجة التصريحية

في البرمجة التصريحية، توضح ماذا يجب حسابه، وليس كيف — حيث تحدد بيئة التشغيل الخطوات. نوعان:

  • البرمجة الوظيفية — مبنية من دوال نقية (بدون آثار جانبية؛ نفس المدخلات تعطي دائمًا نفس المخرجات) مُركَّبة معًا. أمثلة: Haskell, Lisp.
  • البرمجة المنطقية — تُسجّل الحقائق والقواعد؛ تجيب المحرك عن هدف (استعلام) بالاستنتاج. مثال: Prolog.

مثال تصريحي مألوف هو SQL: SELECT * FROM Customer WHERE Country = 'UK' يوضح ما تريده، لا كيفية التنقل عبر السجلات.

الحقائق والقواعد والأهداف هي ما يختبره الامتحان في النموذج التصريحي. بناءً على هذه الحقائق (العبارات الصحيحة) وقاعدة (استنتاج صحيح عندما تتحقق شروطها):

01 type(leopard, wild).
02 type(lion, wild).
03 type(tabby, domestic).
04 size(leopard, large).
05 size(lion, large).
06 size(tabby, small).
07 dangerous(X) IF type(X, wild) AND size(X, large).

"اكتب نتيجة الهدف type(X, wild)":* X = leopard, X = lion. تطابق المحرك الهدف مع كل حقيقة على التوالي؛ كل تطابق يُعدّ حلاً، والحرف الكبير هو متغير يملأه التطابق. "اكتب حقيقة لتبين أن الفهد برّي": type(cheetah, wild). "اشرح ماذا تفعل السطر 07": يُعرّف قاعدة بـ结论 dangerous(X)، وهي صحيحة لأي X يكون برّيًا وكبيرًا، لذا dangerous(A) تُرجع A = leopard, A = lion. "اكتب قاعدة: ميزة F قد تكون متاحة لنمط جسم B إذا كان F ميزة وكان B نمط جسم ولم يكن F غير متاح لـ B": may_be_available(F, B) IF feature(F) AND body_style(B) AND NOT unavailable(F, B). انسخ أسماء التوابعترتيب الحجج المستخدمة في حقائق السؤال؛ تنتهي الحقيقة الجديدة بنقطة، وشروط القاعدة مُربوطة بـ AND.

مقارنة النماذج

النموذج القوة لغات نموذجية
منخفضة المستوى تحكم كامل، سرعة assembly
أمرية مباشرة، بديهية C, Python
كائنية معيارية، تحاكي الكيانات Java, C#, Python
وظيفية واضحة، بدون آثار جانبية Haskell, F#
منطقية استنتاج، قواعد Prolog
قواعد بيانات استعلامات البيانات SQL

اللغات الحديثة غالبًا ما تخلط النماذج — تدعم Python جميع أنواع البرمجة الإجرائية، كائنية، ووظيفية. الاختيار الصحيح يعتمد على المشكلة.

Explore · ⁨استكشف⁩

Programming concept lab · ⁨معمل مفاهيم البرمجة⁩

Connect examples to the programming idea they show. · ⁨صل الأمثلة بالفكرة البرمجية التي تمثلها.⁩

Vocabulary · ⁨مفردات⁩ Train · ⁨تدريب⁩
English العربية
programming paradigm/ˈprəʊɡræmɪŋ ˈpærədaɪm/ منهجية البرمجة
facts/fækts/ الحقائق
rule/ruːl/ القاعدة
low-level/ləʊ ˈlevl/ منخفض المستوى
registers/ˈredʒɪstəz/ مسجلات
memory addresses/ˈmeməri əˈdresɪz/ عناوين الذاكرة
objects/ˈɒbdʒekts/ أشياء
attributes/ˈætrɪbjuːts/ صفات
methods/ˈmeθədz/ الطرق
machine code/məˈʃiːn kəʊd/ كود الآلة
assembly language/əˈsemblɪ ˈlæŋɡwɪdʒ/ لغة التجميع
addressing modes/əˈdresɪŋ məʊdz/ أوضاع العنونة
array/əˈreɪ/ المصفوفة (array)
imperative programming/ɪmˈperətɪv ˈprəʊɡræmɪŋ/ البرمجة الأمرية
Variables/ˈveərɪəblz/ المتغيرات
object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ البرمجة كائنية التوجه
instances/ˈɪnstənsɪz/ الحالات
classes/ˈklæsɪz/ فئات
encapsulation/ɪnˌkæpsjʊˈleɪʃn/ التغليف
inheritance/ɪnˈherɪtəns/ الإرث
subclass/ˈsʌbklæs/ فئة فرعية
superclass/ˈsuːpəklæs/ الكلاس الأب
overriding/ˌəʊvəˈraɪdɪŋ/ إعادة التعريف
polymorphism/ˈpɒlɪmɔːfɪzəm/ تعدد الأشكال
abstraction/əbˈstrækʃn/ التجريد
constructor/kənˈstrʌktə/ الدالة الإنشائية
aggregation/ˌæɡrɪˈɡeɪʃn/ التجميع
containment/kənˈteɪnmənt/ التضمين
declarative programming/dɪˈklærətɪv ˈprəʊɡræmɪŋ/ البرمجة التصريحية
functional programming/ˈfʌŋkʃənl ˈprəʊɡræmɪŋ/ البرمجة الوظيفية
pure functions/pjʊə ˈfʌŋkʃnz/ دوال نقية
side effects/saɪd ɪˈfekts/ آثار جانبية
logic programming/ˈlɒdʒɪk ˈprəʊɡræmɪŋ/ البرمجة المنطقية
SQL/ˌes kjuː ˈel/ SQL
20.2

File processing · ⁨معالجة الملفات⁩

Syllabus · ⁨المنهج⁩
English
Candidates should be able to: Notes and guidance
Write code to perform file-processing operations Open (in read, write, append mode) and close a file Read a record from a file and write a record to a file Perform file-processing operations on serial, sequential, random files
Show understanding of an exception and the importance of exception handling Know when it is appropriate to use exception handling Write program code to use exception handling
العربية
يجب أن يكون المرشحون قادرين على: ملاحظات وإرشادات
اكتب كوداً لأداء عمليات معالجة الملفات افتح (في وضع القراءة، الكتابة، الإضافة) وأغلق ملفاً اقرأ سجلاً من ملف واكتب سجلاً إلى ملف أجرِ عمليات معالجة الملفات على ملفات متسلسلة، خطية، عشوائية
أظهر فهماً لـ الاستثناء وأهمية معالجة الاستثناءات عرّف متى يكون استخدام معالجة الاستثناءات مناسباً اكتب كوداً برمجياً لاستخدام معالجة الاستثناءات

Source: Cambridge International syllabus · ⁨المصدر: منهج كامبريدج الدولي⁩

English

This extends the file 文件 handling from Topic 10, processing serial, sequential and random (direct-access) files. Pseudocode operations: OPENFILE name FOR READ | WRITE | APPEND (READ opens an existing file, WRITE creates/overwrites, APPEND adds to the end); READFILE name, line; WRITEFILE name, value; CLOSEFILE name; and EOF(name) which is TRUE at the end.

Read a whole file:

Search a file (stop when found):

Updating a file in place

Most languages can't edit a text file in place. Instead: open the original for READ and a temporary file for WRITE; for each line, write the new version if it should change, else the original; close both; then replace the original with the temp file. The same pattern handles deleting lines (skip them) and inserting lines.

Records and random-access files

Opening modes. READ: the file must exist and reading starts at the beginning. WRITE: a new file is created, and an existing file of that name is overwritten. APPEND: writing adds to the end of an existing file. Every file that is opened is closed with CLOSEFILE, and EOF(name) is TRUE when the last item has been read.

Three file organisations. In a serial file the records are in the order they were added; in a sequential file they are in key order; both are read from the start. A random file 随机文件 (direct-access file) stores each record at an address calculated from its key by a hashing 哈希 function, so one record is found without reading the others. Records are declared as a user-defined type:

The random-file operations in pseudocode are OPENFILE "Acc.dat" FOR RANDOM, SEEK "Acc.dat", Address (move the file pointer to that record), GETRECORD "Acc.dat", Rec (read the record there) and PUTRECORD "Acc.dat", Rec (write the record there). Finding a customer by account number, as Paper 3 sets it:

To store a record, hash its key, SEEK to the address and PUTRECORD, stepping on past any slot already occupied. Marks go to the hash, the SEEK before the GET or PUT, the comparison with the target, the handling of a collision, and closing the file.

Worked example. ActiveFile.dat holds AccountRecord records. Write pseudocode that copies every record whose Active field is FALSE to the end of ArchiveFile.dat.

Text files in Python (Paper 4): file = open("HighScore.txt", "r"), then for line in file: with line.strip() and line.split(",") to separate the fields, int(…) to convert a score, and file.close(); to write, open(name, "w") (or "a" to append) and file.write(str(score) + "\n"). A high-score table is read into a list of records, the new score inserted at its place, and the whole list written back. The examiner marks the open with the correct mode, a loop that reads every line, the conversion of text to numbers, and the close.

Pitfalls

Forgetting to close a file (data may be lost); opening for WRITE when you meant APPEND (overwrites everything); reading past EOF; hard-coded paths — a path like /Users/Admin/data.txt breaks on another machine, so use a relative constant such as DataFile = "./data/scores.txt".

العربية

يُعمّل هذا التعامل مع الملف من الموضوع 10، لمعالجة ملفات تسلسلية، متسلسلة وعشوائية (الوصول المباشر). عمليات الشبه كود: OPENFILE name FOR READ | WRITE | APPEND (READ يفتح ملفًا موجودًا، WRITE ينشئ/يحل محل، APPEND يضيف في النهاية)؛ READFILE name, line؛ WRITEFILE name, value؛ CLOSEFILE name؛ وEOF(name) التي تكون TRUE في النهاية.

اقرأ الملف بالكامل:

OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") DO
    READFILE "names.txt", thisName
    OUTPUT thisName
ENDWHILE
CLOSEFILE "names.txt"

ابحث في ملف (توقف عند العثور):

found ← FALSE
OPENFILE "people.txt" FOR READ
WHILE NOT EOF("people.txt") AND NOT found DO
    READFILE "people.txt", line
    IF line = target THEN
        found ← TRUE
    ENDIF
ENDWHILE
CLOSEFILE "people.txt"

تحديث ملف في مكانه

معظم اللغات لا يمكنها تعديل ملف نصي في مكانه. بدلاً من ذلك: افتح الأصلي للـ READ وملف مؤقت للـ WRITE؛ لكل سطر، اكتب النسخة الجديدة إذا كان يجب تغييره، وإلا اكتب الأصلية؛ أغلق الاثنين؛ ثم استبدل الأصلي بالمؤقت. نفس النمط يعالج حذف الأسطر (تخطيها) وإدراجها.

تحديث ملف في مكانه: قراءة الملف الأصلي، كتابة الأسطر المعدلة إلى ملف مؤقت، ثم استبدال الأصلي بالمؤقت
تحديث ملف في مكانه: قراءة الأصلي، كتابة التعديلات إلى ملف مؤقت، ثم استبدال الأصلي

سجلات وملفات الوصول العشوائي

وضع فتح. READ: يجب أن يوجد الملف ويبدأ القراءة من البداية. WRITE: يتم إنشاء ملف جديد، ويتم حل محل ملف موجود بنفس الاسم. APPEND: الكتابة تضيف إلى نهاية ملف موجود. يُغلق كل ملف مفتوح بـ CLOSEFILE، وتكون EOF(name) TRUE عند قراءة آخر عنصر.

ثلاث تنظيمات للملفات. في ملف تسلسلي تكون السجلات بالترتيب الذي أضيفت فيه؛ في ملف متسلسل تكون بترتيب المفتاح؛ كلاهما يُقرأ من البداية. ملف عشوائي (ملف الوصول المباشر) يخزن كل سجل عند عنوان محسوب من مفتاحه بواسطة دالة تشفير (Hashing)، بحيث يُوجد سجل واحد دون قراءة البقية. تُصنّع السجلات كنوع محدد مسبقًا من المستخدم:

TYPE AccountRecord
    DECLARE AccNo : INTEGER
    DECLARE Name : STRING
    DECLARE Balance : REAL
    DECLARE Active : BOOLEAN
ENDTYPE
مفتاح 2317 مشفر بـ MOD 1000 إلى العنوان 317، ثم SEEK وGETRECORD على ملف Acc.dat، موضحًا كصف من خانات سجلات متساوية الحجم مع تظليل خانة 317
إيجاد سجل واحد في ملف عشوائي: المفتاح مشفر إلى عنوان، يتجه مؤشر الملف مباشرة إلى تلك الخانة ويُقرأ السجل؛ لا يُلمس أي سجل آخر

عمليات ملف الوصول العشوائي في الشبه كود هي OPENFILE "Acc.dat" FOR RANDOM، SEEK "Acc.dat", Address (تحريك مؤشر الملف إلى ذلك السجل)، GETRECORD "Acc.dat", Rec (قراءة السجل هناك) وPUTRECORD "Acc.dat", Rec (كتابة السجل هناك). إيجاد عميل برقم الحساب، كما وضعته Paper 3:

DECLARE Rec : AccountRecord
DECLARE Target, Address : INTEGER
INPUT Target
Address ← Target MOD 1000              // the hashing function
OPENFILE "Acc.dat" FOR RANDOM
SEEK "Acc.dat", Address
GETRECORD "Acc.dat", Rec
WHILE Rec.AccNo <> Target AND Rec.AccNo <> 0    // 0 marks an empty slot
    Address ← Address + 1               // a collision: try the next slot
    SEEK "Acc.dat", Address
    GETRECORD "Acc.dat", Rec
ENDWHILE
IF Rec.AccNo = Target THEN
    OUTPUT Rec.Name, Rec.Balance
ELSE
    OUTPUT "No such account"
ENDIF
CLOSEFILE "Acc.dat"

لتخزين سجل، شفر مفتاحه، SEEK إلى العنوان وPUTRECORD، متجاوزًا أي خانة مشغولة بالفعل. تُمنح العلامات للتشفير، الـ SEEK قبل GET أو PUT، المقارنة مع المستهدف، ومعالجة الاصطدام، وإغلاق الملف.

مثال محلول. ActiveFile.dat يحتوي على AccountRecord سجلات. اكتب شبه كود ينسخ كل سجل يكون مجال Active فيه FALSE إلى نهاية ArchiveFile.dat.

DECLARE Rec : AccountRecord
OPENFILE "ActiveFile.dat" FOR READ
OPENFILE "ArchiveFile.dat" FOR APPEND
WHILE NOT EOF("ActiveFile.dat")
    READFILE "ActiveFile.dat", Rec
    IF Rec.Active = FALSE THEN
        WRITEFILE "ArchiveFile.dat", Rec
    ENDIF
ENDWHILE
CLOSEFILE "ActiveFile.dat"
CLOSEFILE "ArchiveFile.dat"

ملفات النص في Python (Paper 4): file = open("HighScore.txt", "r")، ثم for line in file: مع line.strip() وline.split(",") لفصل الحقول، int(…) لتحويل درجة، وfile.close()؛ للكتابة، open(name, "w") (أو "a" للإضافة) وfile.write(str(score) + "\n"). تُقرأ جدول أعلى الدرجات في قائمة سجلات، تُدرج الدرجة الجديدة في مكانها، وتُكتب القائمة كاملة مرة أخرى. يمنح المصحح العلامات للفتح بالوضع الصحيح، وحلقة تقرأ كل سطر، وتحويل النص إلى أرقام، والإغلاق.

فخاخ

نسيان إغلاق الملف (قد تُفقد البيانات)؛ الفتح للـ WRITE بينما كنت تقصد APPEND (يحل محل كل شيء)؛ القراءة beyond EOF؛ المسارات الثابتة — مثل مسار /Users/Admin/data.txt لا يعمل على جهاز آخر، لذا استخدم ثابتًا نسبيًا مثل DataFile = "./data/scores.txt".

Explore · ⁨استكشف⁩

File access route · ⁨مسار الوصول إلى الملف⁩

Follow a file from storage to program and back safely. · ⁨اتبع ملفاً من التخزين إلى البرنامج وعده بأمان.⁩

Vocabulary · ⁨مفردات⁩ Train · ⁨تدريب⁩
English العربية
file/faɪl/ ملف
random file/ˈrændəm faɪl/ ملف عشوائي
hashing/ˈhæʃɪŋ/ التجزئة
20.2

Exception handling · ⁨التعامل مع الاستثناءات⁩

English

An exception 异常 is an error or unexpected condition during execution — divide by zero, file not found, network failure, an array 数组 index out of range. Exception handling 异常处理 lets a program detect it and respond gracefully instead of crashing.

It matters because real programs face errors that cannot be prevented up front (files moved, networks down, bad input); without it, every operation needs its own IF check; and it separates the normal flow from the error handling, so the main path reads cleanly. For example, a file may be deleted by another user between your program checking it exists and actually opening it — you cannot prevent that, only handle the failure when it happens.

"Describe, with an example, what is meant by an exception" (two marks). An unexpected event or error that occurs during the execution of a program (at run time) and interrupts its normal flow; for example dividing by zero, opening a file that does not exist, converting non-numeric input to an integer, an array index out of range, or running out of memory. "Identify two possible causes of exceptions" is answered from that list, plus "a device or network is not available" and "invalid data type entered".

"State the reasons for including exception handling" (three marks). To stop the program crashing (terminating unexpectedly); to output a meaningful message to the user rather than a system error; to allow the program to recover and continue, for example by asking for the input again, or to close files safely before it ends; and because some errors cannot be predicted when the program is written. "Describe how program termination due to an exception can be avoided": put the statements that might raise the exception inside a TRY block; write an EXCEPT (catch) block for that exception that handles it, for example by outputting a message, so that execution continues after the block instead of stopping. "Explain what is meant by exception handling": detecting an exception when it occurs and running code (the handler) that deals with it so that the program continues.

Pattern

The TRY block holds the code that might fail; the first matching EXCEPT block runs. Real languages also have a catch-all EXCEPT and a FINALLY block that runs whether or not an exception happened — useful for cleanup (closing files).

Raising an exception

A subroutine that detects an error can raise 抛出 an exception so the caller handles it:

Where to handle exceptions

Handle them close to the error if the response is simple (a message, a retry), or higher up the call stack 调用栈 if only the outer code knows what to do (a top-level GUI loop logs the error and shows a friendly dialog). Don't swallow exceptions silently — at least log them, or debugging becomes impossible.

Common exceptions: FileNotFound, IOError, DivisionByZero, IndexOutOfRange, InvalidArgument, NullReference, OutOfMemory. Wrapping each failing operation in a TRY with the right EXCEPT handlers gives a program that degrades gracefully instead of crashing.

Worked example (Paper 4). Write a function that reads whole numbers, one per line, from a file whose name is passed as a parameter and returns them in a list. It must not crash if the file does not exist or a line is not a whole number.

The try block holds the code that can fail (the open and the conversion); each except names one exception and does something useful; the function still returns a list, so the caller continues. In Java the same shape is try { … } catch (FileNotFoundException e) { … } catch (NumberFormatException e) { … }; in VB.NET Try … Catch ex As FileNotFoundException … End Try. Marks: the risky statements inside the try, the correct exception names, a message for each, and the program continuing afterwards; a catch-all except: gets the crash mark but not the "appropriate exception" mark.

Worked example. A text file of members needs one member's phone number changed. Why can the program not simply overwrite that line, and what is the pattern? A text file's lines are different lengths, and the file has no gaps to absorb a difference: a longer replacement would run into the next record, and a shorter one would leave part of the old line behind. So the pattern is to open the original for READ and a temporary file for WRITE, read every line in turn, writing the new version for the line that changes and the original line for all the others, close both, then replace the original with the temporary file. The same shape handles deleting (skip the line) and inserting (write the extra line). Note that every line gets written, not only the changed one - writing just the new record and losing the rest of the file is the classic slip.

العربية

الاستثناء هو خطأ أو حالة غير متوقعة أثناء التنفيذ — القسمة على صفر، ملف غير موجود، فشل الشبكة، فهرس مصفوفة خارج النطاق. يسمح معالجة الاستثناءات للبرنامج باكتشافها والتفاعل معها بلطف بدلاً من انهياره.

يهم ذلك لأن البرامج الحقيقية تواجه أخطاء لا يمكن منعها مسبقاً (تم نقل الملفات، انقطاع الشبكات، إدخال خاطئ)؛ بدونها، تحتاج كل عملية إلى التحقق IF خاص بها؛ وتفصل بين التدفق الطبيعي ومعالجة الأخطاء، مما يجعل المسار الرئيسي نظيفاً. على سبيل المثال، قد يحذف مستخدم آخر ملفاً بينما يتحقق برنامجك من وجوده وفتحه فعلياً — لا يمكنك منع ذلك، بل فقط التعامل مع الفشل عند وقوعه.

"صِف، بمثال، ما يُقصد بالاستثناء" (علامتان). حدث غير متوقع أو خطأ يحدث أثناء تنفيذ البرنامج (وقت التشغيل) ويقطع تدفقه الطبيعي؛ مثل القسمة على صفر، فتح ملف غير موجود، تحويل إدخال غير رقمي إلى عدد صحيح، فهرس مصفوفة خارج النطاق، أو نفاد الذاكرة. "حدد سببين محتملين للاستثناءات" يُجاب عنه من تلك القائمة، بالإضافة إلى "الجهاز أو الشبكة غير متاح" و"تم إدخال نوع بيانات غير صالح".

"اذكر أسباب تضمين معالجة الاستثناء" (ثلاث علامات). لمنع البرنامج من الانهيار (التوقف بشكل غير متوقع)؛ لإخراج رسالة ذات معنى للمستخدم بدلاً من خطأ النظام؛ للسماح للبرنامج بالاستعادة والاستمرار، على سبيل المثال بطلب الإدخال مرة أخرى، أو إغلاق الملفات بأمان قبل انتهائه؛ ولأن بعض الأخطاء لا يمكن التنبؤ بها عند كتابة البرنامج. "وصف كيفية تجنب إنهاء البرنامج بسبب استثناء": ضع الجمل التي قد تثير الاستثناء داخل كتلة TRY؛ اكتب كتلة EXCEPT (مقبض) لذلك الاستثناء تتعامل معه، على سبيل المثال بإخراج رسالة، حتى يستمر التنفيذ بعد الكتلة بدلاً من التوقف. "اشرح ما يُقصد بمعالجة الاستثناءات": اكتشاف الاستثناء عند وقوعه وتشغيل الكود (المقبض) الذي يتعامل معه حتى يستمر البرنامج.

النمط

TRY
    OPENFILE "data.txt" FOR READ
    READFILE "data.txt", line
    OUTPUT line
    CLOSEFILE "data.txt"
EXCEPT FileNotFound
    OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
    OUTPUT "Sorry, error reading the file."
ENDTRY

كتلة TRY تحتوي على الكود الذي قد يفشل؛ كتلة EXCEPT الأولى المتطابقة تعمل. اللغات الحقيقية أيضاً تحتوي على مقبض شامل EXCEPT وكتلة FINALLY تعمل سواء حدث استثناء أم لا — مفيدة للتنظيف (إغلاق الملفات).

تدفق الاستثناء: إذا أثار كتلة TRY استثناءً، ينتقل التحكم إلى EXCEPT المطابق؛ بدون استثناء يتم تخطيها. في كلتا الحالتين تعمل كتلة FINALLY، ثم يستمر البرنامج *تدفق الاستثناء: يقفز الاستثناء إلى EXCEPT المطابق؛ كتلة FINALLY تعمل دائماً قبل أن يستمر البرنامج

إثارة استثناء

الوظيفة الفرعية التي تكتشف الخطأ يمكنها إثارة استثناء لكي يتعامل معه الداع:

PROCEDURE Divide(a : INTEGER, b : INTEGER) RETURNS INTEGER
    IF b = 0 THEN
        RAISE DivideByZero
    ENDIF
    RETURN a DIV b
ENDPROCEDURE

حيث يتم التعامل مع الاستثناءات

تعامل معها قريباً من الخطأ إذا كانت الاستجابة بسيطة (رسالة، إعادة المحاولة)، أو أعلى في مكدس الاستدعاءات إذا كان الكود الخارجي فقط يعرف ما يجب فعله (حلقة واجهة رسومية عليا تسجل الخطأ وتعرض حواراً ودوداً). لا ابتلع الاستثناءات بصمت — على الأقل سجلها، وإلا يصبح التصحيح مستحيلاً.

استثناءات شائعة: FileNotFound، IOError، DivisionByZero، IndexOutOfRange، InvalidArgument، NullReference، OutOfMemory. تغليف كل عملية فاشلة في TRY مع المعالجات EXCEPT الصحيحة يمنح برنامجًا يتدهور بشكل لطيف بدلاً من الانهيار.

مثال محلول (ورقة 4). اكتب دالة تقرأ أعداداً صحيحة، واحد لكل سطر، من ملف يكون اسمه مُمرراً كمعامل وتعيدها في قائمة. لا يجب أن ينهار إذا لم يكن الملف موجوداً أو لم يكن السطر عدداً صحيحاً.

def read_scores(filename):
    scores = []
    try:
        file = open(filename, "r")
        for line in file:
            scores.append(int(line))
        file.close()
    except FileNotFoundError:
        print("The file", filename, "does not exist")
    except ValueError:
        print("A line in the file was not a whole number")
    return scores

كتلة try تحتوي على الكود الذي يمكن أن يفشل (الفتح والتحويل)؛ كل except يسمي استثناءً واحداً ويفعل شيئاً مفيداً؛ لا تزال الدالة تعيد قائمة، لذا يستمر الداع. في Java نفس الشكل هو try { … } catch (FileNotFoundException e) { … } catch (NumberFormatException e) { … }؛ في VB.NET Try … Catch ex As FileNotFoundException … End Try. العلامات: الجمل الخطرة داخل try، أسماء الاستثناءات الصحيحة، رسالة لكل منها، واستمرار البرنامج afterwards؛ مقبض شامل except: يحصل على علامة الانهيار لكن ليس علامة "الاستثناء المناسب".

مثال محلول. ملف نصي للأعضاء يحتاج تغيير رقم هاتف عضو واحد. لماذا لا يمكن للبرنامج ببساطة الكتابة فوق هذا السطر، وما هو النمط؟ أسطر الملف النصي أطوال مختلفة، والملف لا يحتوي على فراغات لامتصاص الفرق: بديل أطول سيصطدم بالسجل التالي، وبديل أقصر سيترك جزءاً من السطر القديم خلفه. لذا النمط هو فتح الأصلي لـ READ وملف مؤقت لـ WRITE، قراءة كل سطر على التوالي، كتابة النسخة الجديدة للسطر المتغير والأصلية لجميع الأخرى، إغلاق كليهما، ثم استبدال الأصلي بالمؤقت. نفس الشكل يعالج الحذف (تخطي السطر) والإدراج (كتابة السطر الإضافي). لاحظ أن كل سطر يتم كتابته، ليس فقط المتغير - كتابة السجل الجديد فقط وفقدان باقي الملف هي الخطأ الكلاسيكي.

Explore · ⁨استكشف⁩

How exception handling flows · ⁨كيف يتدفق التعامل مع الاستثناءات⁩

Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing. · ⁨مرر عبر ما يحدث عند فشل الكود. يقفز الاستثناء خارج التدفق الطبيعي إلى معالج، ينظف FINALLY في الحالتين، ويستمر البرنامج بدلاً من انهياره.⁩

Vocabulary · ⁨مفردات⁩ Train · ⁨تدريب⁩
English العربية
exception/ekˈsepʃn/ استثناء
exception handling/ekˈsepʃn ˈhændlɪŋ/ معالجة الاستثناءات
raise/reɪz/ يرفع
call stack/kɔːl stæk/ مكدس الاستدعاء
20.2

Definitions the examiner accepts · ⁨التعريفات التي يقبلها المصحح⁩

English

A definition question is marked against fixed wording. Learn these exactly, and give one answer only.

Term Definition
programming paradigm a style or way of programming, with its own way of structuring a program
imperative language the program is a sequence of statements that change the program's state; the programmer says how the task is done
declarative language the program states facts and rules and the inference engine works out how to find the answer
class a template defining the attributes and methods of the objects of that type
object (instance) an occurrence of a class, with its own values for the attributes
attribute a data item that belongs to a class
method a procedure or function that belongs to a class and acts on its attributes
encapsulation keeping the attributes and methods together in a class and restricting external access to the data, so that it is changed only through public methods
inheritance a subclass acquires the attributes and methods of its parent class and can add or override them
polymorphism methods with the same name that behave differently for different classes
constructor a method that runs when an object is created and initialises its attributes
containment a class has an object of another class as one of its attributes
fact a statement in a declarative program that is true
rule a conclusion that holds when its conditions are true
serial, sequential, random file records in the order added; records in key order; each record at an address calculated from its key
exception an unexpected error or event during execution that interrupts the normal flow
exception handling detecting an exception when it occurs and running code that deals with it so that the program continues
العربية

تُصنّف أسئلة التعريف بناءً على صياغة ثابتة. احفظ هذه التعريفات بدقة، وقدم إجابة واحدة فقط.

مصطلح تعريف
نمط برمجي أسلوب أو طريقة للبرمجة، بطريقة خاصة في هيكلة البرنامج
لغة أمرية البرنامج عبارة عن سلسلة من التعليمات تغير حالة البرنامج؛ المبرمج يقول كيف تُنفذ المهمة
لغة إعلانية البرنامج يعلن حقائق وقواعد ومحرك الاستنتاج يحسب كيفية العثور على الإجابة
فئة قالب يحدد الخصائص والأساليب للكائنات من ذلك النوع
كائن (مثيل) حدوث للفئة، بقيم خاصة به للخصائص
خاصية عنصر بيانات ينتمي إلى فئة
أسلوب إجراء أو دالة تنتمي لفئة وتعمل على خصائصها
التغليف الاحتفاظ بالخصائص والوظائف معًا داخل فئة وتقييد الوصول الخارجي إلى البيانات، بحيث لا يتم تغييرها إلا من خلال الوظائف العامة
الوراثة تكتسب الفئة الفرعية خصائص ووظائف فئتها الأم ويمكنها إضافة أو استبدالها
تعددية الأشكال وظائف تحمل نفس الاسم ولكن تتصرف بشكل مختلف حسب الفئات المختلفة
الدالة البانية دالة تُنفَّذ عند إنشاء كائن وتمنح خصائصه
الانتماء تمتلك فئة ما كائنًا من فئة أخرى كواحدة من خصائصها
حقيقة عبارة في برنامج إعلاني تكون صحيحة
قاعدة استنتاج يتحقق عندما تكون شروطه صحيحة
ملف تسلسلي، متتابع، عشوائي السجلات按照 الإضافة؛ السجلات按照 ترتيب المفتاح؛ كل سجل على عنوان محسوب من مفتاحه
استثناء خطأ أو حدث غير متوقع أثناء التنفيذ يعطل التدفق الطبيعي
معالجة الاستثناءات اكتشاف الاستثناء عند وقوعه وتشغيل الكود الذي يتعامل معه حتى يستمر البرنامج
20.2

Exam tips · ⁨نصائح للامتحان⁩

English
  • Paradigms: know the one-line description of each and be ready to name the paradigm from a code sample; low-level questions want the five addressing modes and what the accumulator receives.
  • OOP definitions come up every session: class, object, attribute, method, encapsulation, inheritance, polymorphism, constructor. Write a class in pseudocode with PRIVATE attributes, a PUBLIC NEW and getters; a subclass with INHERITS and SUPER.NEW.
  • Declarative: a goal with a variable returns every matching fact; a rule is a conclusion IF conditions joined with AND; copy the question's predicate names exactly.
  • Files: the three modes and what each does to an existing file; READFILE in a WHILE NOT EOF loop; random files use a hash, SEEK, GETRECORD and PUTRECORD, with a step-on for collisions.
  • Exceptions: definition with an example, three reasons for handling them, and TRY with a named EXCEPT that lets the program continue.

Common mistakes

  • Describing a declarative program as "a sequence of steps that gives the answer"; it states what is true and what is wanted, not how.
  • Confusing an object with a class, or an instance with an attribute; the question "an occurrence of an object" wants instance.
  • Declaring the attributes PUBLIC, or reaching them from outside the class instead of through a getter, which loses the encapsulation marks.
  • A subclass constructor that sets the parent's attributes directly instead of calling SUPER.NEW.
  • Explaining polymorphism as "many objects"; it is the same method name behaving differently for different classes.
  • Opening a file FOR WRITE to add a record, which destroys the existing contents; use APPEND.
  • Reading a random file from the start; SEEK to the hashed address first.
  • Putting the exception handler around code that cannot fail, or catching everything with no message, or describing exception handling as "checking the input with IF".
العربية
  • النماذج: تعرف الوصف الخطي الواحد لكل نموذج وكن مستعدًا لتسمية النموذج من عينة برمجية؛ الأسئلة منخفضة المستوى تريد أوضاع العنونة الخمسة وما يستقبله المجمع.
  • تعريفات البرمجة كائنية-directions تظهر في كل جلسة: فئة، كائن، خاصية، وظيفة، تغليف، وراثة، تعددية أشكال، دالة بانية. اكتب فئة بلغة وهمية بخصائص خاصة ودالة بانية عامة وجوالب؛ فئة فرعية ترث وتستخدم دالة بانية أم.
  • إعلانية: هدف بمتغير يعيد كل حقيقة مطابقة؛ القاعدة هي استنتاج إذا كانت الشروط مرتبطة بـ AND؛ انسخ أسماء القواعد من السؤال حرفيًا.
  • الملفات: الأوضاع الثلاثة وما يفعلونه في ملف موجود؛ قراءة ملف في حلقة بينما ليس نهاية الملف؛ الملفات العشوائية تستخدم تجزئة، بحث، جلب سجل ووضع سجل، مع خطوة فوق للتصادمات.
  • الاستثناءات: التعريف بمثال، ثلاثة أسباب لمعالجتها، وحاول مع استثناء مسمى يسمح للبرنامج بالاستمرار.

أخطاء شائعة

  • وصف برنامج إعلاني بأنه "تسلسل خطوات يعطي الإجابة"؛ هو يحدد ما هو صحيح وما هو مطلوب، وليس كيف.
  • الخلط بين كائن وفئة، أو مثال وخاصية؛ السؤال "حدوث لكائن" يريد مثالاً.
  • إعلان الخصائص عامة، أو الوصول إليها من خارج الفئة بدلاً من عبر جواب، مما يفقد علامات التغليف.
  • دالة بانية فرعية تضع خصائص الأم مباشرةً بدلاً من استدعاء دالة بانية أم.
  • شرح تعددية الأشكال بأنها "كثير من الكائنات"؛ هي نفس اسم الوظيفة يتصرف بشكل مختلف حسب الفئات المختلفة.
  • فتح ملف للكتابة لإضافة سجل، مما يدمر المحتوى الموجود؛ استخدم الإضافة.
  • قراءة ملف عشوائي من البداية؛ ابحث عن العنوان المجزأ أولاً.
  • وضع معالج الاستثناء حول الكود الذي لا يمكن أن يفشل، أو التقاط كل شيء بدون رسالة، أو وصف معالجة الاستثناءات بأنها "فحص الإدخال باستخدام IF".

Interactive lessons on this topic · ⁨دروس تفاعلية حول هذا الموضوع⁩

Work through it step by step, with instant-check exercises. · ⁨ا-working عليه خطوة بخطوة، مع تمارين تحقق فوري.⁩

Past Papers · ⁨أوراق الامتحانات السابقة⁩

More topics in A-Level Computer Science · ⁨A-Level علوم الحاسوب⁩ · ⁨المزيد من المواضيع في A-Level Computer Science · ⁨A-Level علوم الحاسوب⁩⁩

Log in or create account · ⁨تسجيل الدخول أو إنشاء حساب⁩

IGCSE, A-Level & AP