This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · تحتاج هذه الصفحة إلى متصفح حديث (يدعم SharedArrayBuffer). يرجى تحديث Chrome أو Edge أو Firefox أو Safari إلى أحدث إصدار.
Python runs your code one line at a time. Each line is a statement 语句. A program 程序 is just a list of statements that run from top to bottom.
The print() function shows text on the screen. This is called output 输出. Text inside quotes is a string 字符串.
Each print() starts a new line.
Quotes can be "double" or 'single' — both make a string.
A program does nothing until you run it.
العربية
بايثون يشغل كودك سطرًا تلو الآخر. كل سطر هو تعليمة. البرنامج مجرد قائمة من التعليمات تُنفذ من الأعلى إلى الأسفل.
دالة print() تعرض النص على الشاشة. هذا يسمى الإخراج. النص داخل علامات الاقتباس هو نصي (سلسلة)
print("Hello, world!")
print("I am learning Python")
كل print() يبدأ سطرًا جديدًا.
يمكن أن تكون علامات الاقتباس "double" أو 'single' — كلاهما يُنتج نصًا.
لا يقوم البرنامج بأي شيء حتى تقوم بتشغيله.
الكود المصدري يمر عبر المفسر لإنتاج إخراج
1.2
التعليقات ونمط الكود
English
A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.
Good style makes code easy to read:
Use clear names that say what a value means.
Put one statement on each line.
Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
العربية
التعليق يبدأ بـ #. يتجاهل بايثون كل ما بعد # في ذلك السطر. التعليقات تشرح كودك للناس؛ وهي لا تغير ما يفعله الكود.
# This line is a note for humans
print("Hi") # you can also comment at the end of a line
النمط الجيد يجعل الكود سهل القراءة:
استخدم أسماء واضحة تعبر عن معنى القيمة.
ضع تعليمة واحدة في كل سطر.
لا تضيف مسافات في بداية السطر العادي. في بايثون، المسافات في البداية (المسافة البادئة) لها معنى خاص، لذا فإن المسافة الخاطئة تسبب خطأ.
1.3
الإدخال، المعالجة، الإخراج
English
Many programs follow a simple plan: input 输入 → process → output. You get some data, do something with it, then show a result.
The input() function reads text that the user types. It always gives back a string.
input() waits for the user to type and press Enter.
Store the typed text in a variable 变量 so you can use it later.
Because input() returns a string, change it with int(...) first if you need a number.
Common mistakes
Forgetting the quotes: print(Hello) looks for a variable named Hello and raises a NameError. Text needs quotes: print("Hello").
A stray space at the start of a line: Python reads indentation as structure, so it raises an IndentationError.
Assuming input() returns a number. It always returns a string, so wrap it in int(...) before doing any maths.
العربية
تتبع العديد من البرامج خطة بسيطة: إدخال → معالجة → إخراج. تحصل على بعض البيانات، تقوم بشيء ما بها، ثم تعرض النتيجة.
دالة input() تقرأ النص الذي يكتبه المستخدم. تُرجع دائمًا نصًا (string).
name = input("What is your name? ")
print("Hello, " + name)
input() ينتظر المستخدم ليقوم بالكتابة والضغط على Enter.
احفظ النص المكتوب في متغير لتتمكن من استخدامه لاحقًا.
نظرًا لأن input() تُرجع نصًا، قم بتحويلها باستخدام int(...) أولًا إذا كنت بحاجة إلى رقم.
أخطاء شائعة
نسيان علامات التنصيص: print(Hello) تبحث عن متغير باسم Hello وتُثير NameError. النص يحتاج إلى تنصيص: print("Hello").
مسافة زائدة في بداية السطر: بايثون يقرأ المسافة البادئة كهيكل، لذا تُثير IndentationError.
افتراض أن input() تُرجع رقمًا. إنها تُرجع دائمًا نصًا، لذا غلفها بـ int(...) قبل إجراء أي عمليات حسابية.
2Variables, types & operators · المتغيرات، الأنواع والعمليات
A variable 变量 is a name for a value 值. You make one with =, which is called assignment 赋值. The name goes on the left; the value goes on the right.
Now age holds 17. Use the name anywhere you need the value, and change it later:
The = sign does not mean "equal". It means "store the right side under the left name".
To test if two values are equal, use == (see below).
العربية
المتغير هو اسم للقيمة. تنشئه باستخدام =، والذي يُسمى التعيين. الاسم يكون على اليسار؛ القيمة تكون على اليمين.
age = 17
name = "Mei"
price = 9.99
print(age, name, price)
الآن age يحتوي على 17. استخدم الاسم أينما تحتاج القيمة، وغيّرها لاحقًا:
age = 17
age = age + 1 # age is now 18
print(age)
يشير كل اسم متغير إلى قيمة في الذاكرة
علامة = لا تعني "يساوي". بل تعني "احفظ الجانب الأيمن تحت الاسم الأيسر".
لاختبار ما إذا كانت قيمتان متساويتين، استخدم == (أنظر أدناه).
2.2
الأرقام: int & float
English
Python has two main number types. An integer 整数 (int) is a whole number like 17. A float 浮点数 (float) has a decimal point like 9.99.
These operators 运算符 work on numbers:
Operator
Meaning
Example
Result
+
add
3 + 2
5
-
subtract
3 - 2
1
*
multiply
3 * 2
6
/
divide (always float)
7 / 2
3.5
//
integer divide
7 // 2
3
%
remainder (modulo)
7 % 2
1
**
power
2 ** 3
8
/ always gives a float, so 4 / 2 is 2.0.
// and % go together: 17 // 5 is 3, and 17 % 5 is 2.
العربية
يحتوي بايثون على نوعين رئيسيين للأرقام. العدد الصحيح (int) هو عدد صحيح مثل 17. الكسر العشري (float) يحتوي على نقطة عشرية مثل 9.99.
تعمل هذه العمليات الحسابية على الأرقام:
العملية
المعنى
المثال
النتيجة
+
إضافة
3 + 2
5
-
طرح
3 - 2
1
*
ضرب
3 * 2
6
/
قسمة (دائماً كسر عشري)
7 / 2
3.5
//
قسمة صحيحة
7 // 2
3
%
باقي القسمة (modulo)
7 % 2
1
**
أس (قوة)
2 ** 3
8
/ تُرجع دائمًا كسرًا عشريًا، لذا 4 / 2 هي 2.0.
// و% يعملان معًا: 17 // 5 هي 3، و17 % 5 هي 2.
2.3
التعبيرات وتحويل النوع
English
An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.
input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:
int("abc") fails, so only convert text that looks like a number.
Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
العربية
التعبير هو أي شيء له قيمة، مثل 3 + 4 * 2. يستخدم بايثون ترتيب العمليات الحسابية الطبيعي (* و/ قبل + و-)؛ أضف أقواس لجعل الترتيب واضحًا.
input() تُرجع نصًا، لذا حولها قبل إجراء العمليات الحسابية. تغيير قيمة من نوع إلى آخر هو تحويل النوع (type conversion):
age = int("17") # text "17" -> number 17
price = float("9.99") # text -> 9.99
label = str(17) # number -> text "17"
print(age, price, label)
int("abc") تفشل، لذا حوّل فقط النصوص التي تشبه الأرقام.
خلط الأنواع يفشل أيضًا: "age: " + 17 هو خطأ؛ اكتب "age: " + str(17).
2.4
المنطق والمقارنة
English
A Boolean 布尔值 is one of just two values: True or False. A comparison 比较 gives back a Boolean.
Operator
Meaning
==
equal to
!=
not equal to
<>
less than / greater than
<=>=
less / greater than or equal to
Join comparisons with and, or, not:
Common mistakes
/ always gives a float, even 4 / 2 is 2.0. Use // when you want a whole number.
Using = where you mean ==: = assigns a value, == tests whether two values are equal.
Joining a string and a number: "age: " + 5 raises a TypeError. Convert first with str(5).
Floats are not exact, so 0.1 + 0.2 is not exactly 0.3 — avoid == on float results.
العربية
القيمة المنطقية (Boolean) هي واحدة من قيمتين فقط: True أو False. المقارنة تُرجع قيمة منطقية.
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value, end=" ")
print() # 1 2 3 4
6.4
استيعاب القوائم
English
A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].
Add if to keep only some items.
العربية
استيعاب القائمة يبني قائمة جديدة في سطر واحد: [expression for item in sequence].
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
أضف if للاحتفاظ ببعض العناصر فقط.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
6.5
المجموعات الثابتة والمجموعات
English
A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.
A function that needs to hand back two results returns a tuple:
A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.
Common mistakes
b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
The last item is a[-1]; a[len(a)] is out of range.
append adds ONE item; use extend or + to join another list.
Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
A tuple with one item needs a comma: (5,), not (5).
A set has no order and no duplicates, so you cannot index it with s[0].
العربية
المجموعة الثابتة هي متتالية ثابتة بين أقواس دائرية. لا يمكن تغييرها بعد إنشائها — استخدمها للقيم التي تنتمي معًا، وقم بتفريغها في أسماء.
point = (3, 4)
x, y = point # unpacking
print(x, y) # 3 4
الدالة التي تحتاج إلى إرجاع نتيجتين تُرجع مجموعة ثابتة:
student = {"name": "Mei"}
student["score"] = 88 # add a new key
student["score"] = 90 # update the value
print(student) # {'name': 'Mei', 'score': 90}
التحقق والتكرار
استخدم in لاختبار وجود مفتاح. كرر فوق المفاتيح، أو فوق .items() للحصول على المفتاح والقيمة معًا.
student = {"name": "Mei", "score": 90}
print("score" in student) # True
for key, value in student.items():
print(key, "=", value)
# name = Mei
# score = 90
يُرجع .get(key, default) افتراضيًا عند عدم وجود المفتاح — بدون خطأ.
Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.
Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
العربية
يمكن للكود أن يفشل بثلاث طرق. خطأ في بناء الجملة يكسر قواعد بايثون، لذا لا يعمل أبداً. خطأ وقت التشغيل يحدث أثناء التنفيذ، مثل القسمة على صفر. خطأ منطقي يعمل لكن يعطي إجابة خاطئة.
# A runtime error, caught so this block still finishes:
try:
print(10 / 0)
except ZeroDivisionError:
print("cannot divide by zero")
# cannot divide by zero
يطبع بايثون مسار التتبع (traceback) يُظهر أين فشل. اقرأه من الأسفل إلى الأعلى.
أخطاء بايثون الشائعة: بناء الجملة، الاسم، النوع، الفهرس
9.2
try / except / raise
English
Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.
Catch a specific type (ValueError, ZeroDivisionError, …).
raise makes your own error on purpose.
العربية
حِضّن الكود الخطير في try. إذا فشل، except يلتقط الاستثناء ويتعامل معه بدلاً من انهيار البرنامج.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
try:
set_age(-1)
except ValueError as err:
print("error:", err)
# error: age cannot be negative
9.3
الاختبار والصلابة
English
A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.
Robust 健壮 code does not crash on strange input; it handles it gracefully.
Common mistakes
Do not use a bare except: — catch the specific error, e.g. except ValueError:.
A syntax error stops the whole program before it runs, so fix those first.
Test the edge cases (empty input, zero, the largest value), not just the easy one.
العربية
الاختبار يتحقق من أن الكود يعطي الإجابة الصحيحة. جرب الحالات العادية و حالات الحواف — إدخال فارغ، صفر، قيم كبيرة جداً.
A text file 文本文件 stores text on disk. Open it with open(name, mode) where mode 模式 says read or write. Always use with, which closes the file for you.
Writing
Mode "w" writes a new file and erases any old one.
Reading
Mode "r" (the default) reads. .read() returns the whole file as one string.
Line by line
Loop over the file to get one line at a time. .strip() removes 去除 the newline 换行符 at the end.
Appending
Mode "a" appends 追加 — it adds to the end without erasing.
Mode
Meaning
"r"
read (default)
"w"
write (erases first)
"a"
append (add to the end)
Common mistakes
Always close a file, or use with open(...) as f: which closes it for you.
read() gives the whole file as one string, and each line still ends with \n.
Opening with "w" erases the file first; use "a" to add to the end.
العربية
ملف نصي يخزن النص على القرص. افتحه باستخدام open(name, mode) حيث يشير الوضع إلى القراءة أو الكتابة. استخدم دائماً with، الذي يغلق الملف عنك.
الكتابة
وضع "w" يكتب ملفاً جديداً ويمسح أي ملف قديم.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print("saved") # saved
القراءة
وضع "r" (الافتراضي) يقرأ. .read() يُرجع الملف بأكمله كسلسلة واحدة.
with open("notes.txt", "w") as f:
f.write("hello\nworld\n")
with open("notes.txt") as f:
print(f.read().strip()) # hello / world
سطراً بسطر
مرر على الملف للحصول على سطر واحد في كل مرة. .strip() يزيل السطر الجديد في النهاية.
with open("data.txt", "w") as f:
f.write("Mei,88\nSam,71\n")
with open("data.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(name, "scored", score)
# Mei scored 88
# Sam scored 71
الإضافة
وضع "a" يُضيف — يضيف في النهاية دون مسح.
with open("log.txt", "w") as f:
f.write("line 1\n")
with open("log.txt", "a") as f:
f.write("line 2\n")
with open("log.txt") as f:
print(f.read().strip()) # line 1 / line 2
الوضع
المعنى
"r"
قراءة (افتراضي)
"w"
كتابة (يمسح أولاً)
"a"
إضافة (إضافة في النهاية)
أخطاء شائعة
أغلق الملف دائماً، أو استخدم with open(...) as f: الذي يغلقه عنك.
تُعيد read() الملف كاملاً كنص واحد، ولا تزال كل سطر ينتهي بـ \n.
فتحه بـ "w" يمسح الملف أولاً؛ استخدم "a" للإضافة في النهاية.
An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.
Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
العربية
الخوارزمية هي قائمة واضحة من الخطوات تحل مشكلة. التفكيك يعني تقسيم مشكلة كبيرة إلى أجزاء أصغر يمكنك حلها واحداً تلو الآخر.
# Algorithm: find the largest number in a list
def largest(nums):
best = nums[0]
for n in nums:
if n > best:
best = n
return best
print(largest([3, 9, 2, 7])) # 9
التجريد يعني تجاهل التفاصيل: تستخدم largest(...) دون إعادة قراءة كيفية عملها.
11.2
الكود الوهمي والمخططات الانسيابية
English
Pseudocode 伪代码 is plain, structured English for an algorithm, written before the real code. It is not run.
A flowchart 流程图 draws the same plan: a box for each step, a diamond for each decision 判断, and arrows for the order.
العربية
الكود الوهمي هو لغة إنجليزية بسيطة ومنظمة لخوارزمية، تُكتب قبل الكود الحقيقي. لا يتم تشغيله.
SET best TO first number
FOR Each number n
IF n > best
THEN
SET best TO n
OUTPUT best
المخطط الانسيابي يرسم نفس المخطط: مربع لكل خطوة، معين لكل قرار، وأسهم للترتيب.
11.3
الاستدعاء الذاتي ومكدس الاستدعاءات
English
Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).
Each paused call sits on the call stack 调用栈 until the call above it returns.
Common mistakes
Recursion needs a base case, or it calls itself forever and crashes the call stack.
Pseudocode is for planning — it need not run, but every step must be unambiguous.
Break a big problem into small named steps before you write any code.
العربية
الاستدعاء الذاتي هو عندما تستدعي الدالة نفسها. تحتاج إلى حالة أساسية (مدخل بسيط يُرجع فوراً) وحالة استدعاء ذاتي (تستدعي نفسها على مدخل أصغر).
مكدس الاستدعاء لـ factorial(3): كل استدعاء ينتظر، ثم يعود بالترتيب العكسي
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5)) # 120
كل استدعاء متوقف يجلس على مكدس الاستدعاءات حتى يرجع الاستدعاء الذي فوقه.
أخطاء شائعة
الاستدعاء الذاتي يحتاج لحالة أساسية، وإلا يستدعي نفسه إلى ما لا نهاية ويُسبب انهيار مكدس الاستدعاءات.
الكود الوهمي للتخطيط — لا يجب أن يعمل، لكن كل خطوة يجب أن تكون غير غامضة.
قسّم مشكلة كبيرة إلى خطوات صغيرة مسماة قبل كتابة أي كود.
An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.
العربية
نوع بيانات تجريدي (ADT) يصف بعض البيانات بالإضافة إلى العمليات عليها، منفصلة عن كيفية بنائها. تستخدمه من خلال عملياته، وليس من خلال تخزينه الداخلي.
# A stack ADT, built on a list
s = []
s.append(1) # add
s.append(2)
print(s.pop()) # 2 (remove the most recent)
12.2
المكدسات
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
العربية
المكدس هو آخر الداخل، أول الخارج (LIFO). تدفع للأعلى وتُخرج من الأعلى.
A stack removes from the top (LIFO); a queue removes from the front (FIFO)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
الطوابير
English
A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.
العربية
الطابور هو أول الداخل، أول الخارج (FIFO). تضيف في الخلف وتُخرج من الأمام.
queue = []
queue.append("a") # enqueue
queue.append("b")
print(queue.pop(0)) # a (dequeue the front)
print(queue.pop(0)) # b
12.4
القوائم المترابطة
English
A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 to the next node; the last points to None.
العربية
قائمة مترابطة هي سلسلة من العقد. كل عقدة تحتوي على بيانات ومؤشر للعقدة التالية؛ الأخيرة تشير إلى None.
A linked list: each node holds data and a pointer to the next node, ending at None
n3 = {"data": 3, "next": None}
n2 = {"data": 2, "next": n3}
n1 = {"data": 1, "next": n2}
node = n1
while node is not None: # traverse to the end
print(node["data"])
node = node["next"]
# 1 2 3
12.5
الجداولIMATION
English
A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.
العربية
جدول الIMATION يربط مفتاحاً بمكان باستخدام دالة الIMATION. يمكن لمفتاحين أن يسقطا في نفس المكان — تصادم. dict الخاص ببايثون هو جدولIMATION، لذا البحث سريع.
دالة التجزئة تربط كل مفتاح بمكان؛ يمكن أن يتصادم مفتاحان في نفس المكان
A search 查找 finds where a value is. Linear search 线性查找 checks each item in turn, so it works on any list.
Binary search 二分查找 is much faster but needs a sorted list. It halves the range each step.
العربية
البحث يعثر على مكان قيمة ما. البحث الخطي يفحص كل عنصر بالتتابع، لذا يعمل على أي قائمة.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1 # not found
print(linear_search([4, 8, 2, 9], 2)) # 2
البحث الثنائي أسرع بكثير لكنه يتطلب قائمة مرتبة. يقسم النطاق إلى نصفين في كل خطوة.
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
البحث الثنائي يقسم النطاق إلى نصفين في كل خطوة — O(log n) على قائمة مرتبة
13.2
الفرز (فقاعي وإدراج)
English
To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.
Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:
In real code, use Python's built-in sorted():
العربية
الفرز هو وضع العناصر في ترتيب. الفرز الفقاعي يقوم بتبديل الأقران المتتاليين اللذين ليسا في الترتيب الصحيح بشكل متكرر.
def bubble_sort(a):
a = a[:] # work on a copy
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
فرز الإدراج يبني جزءاً مرتباً عن طريق عنصر واحد في كل مرة، مزاحاً كل عنصر جديد للخلف إلى مكانه:
def insertion_sort(a):
a = a[:] # work on a copy
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # shift bigger values right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key # drop key into the gap
return a
print(insertion_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
في الكود الفعلي، استخدم الدالة المدمجة Python sorted():
print(sorted([5, 2, 4, 1])) # [1, 2, 4, 5]
13.3
كفاءة الخوارزميات
English
Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.
Big-O
Name
Example
$O(1)$
constant
look up a dict key
$O(\log n)$
logarithmic
binary search
$O(n)$
linear
linear search
$O(n^2)$
quadratic
bubble sort
العربية
الكفاءة تسأل كيف ينمو العمل مع نمو المدخلات. نصفها باستخدام Big-O.
كيف ينمو عدد الخطوات مع حجم المدخلات للتعقيدات الشائعة
Big-O
الاسم
مثال
$O(1)$
ثابت
البحث عن مفتاح في قاموس
$O(\log n)$
لوغاريتمي
البحث الثنائي
$O(n)$
خطي
البحث الخطي
$O(n^2)$
تربيعي
الفرز الفقاعي
def steps(n): # how many steps a linear scan takes
count = 0
for i in range(n):
count = count + 1
return count
print(steps(100)) # 100 -> O(n)
13.4
العشوائية والمحاكاة
English
The random module makes random numbers. Use a seed 种子 to make results repeatable. A simulation 模拟 runs many random trials to estimate an answer.
Common mistakes
Binary search only works on a sorted list.
Big-O tells you how the time GROWS, not the exact time; an O(n²) method beats O(n) only for tiny inputs.
Bubble sort is O(n²) — fine for learning, but slow on large lists.
العربية
وحدة random تولد أرقاماً عشوائية. استخدم بذرة لجعل النتائج قابلة للتكرار. المحاكاة تشغل تجارب عشوائية عديدة لتقدير إجابة.
import random
random.seed(0)
rolls = [random.randint(1, 6) for _ in range(1000)]
print(rolls.count(6)) # about 1/6 of 1000
أخطاء شائعة
البحث الثنائي يعمل فقط على قائمة مرتبة.
Big-O يخبرك بكيفية نمو الوقت، وليس الوقت الدقيق؛ طريقة O(n²) تفوق O(n) فقط للمدخلات الصغيرة جداً.
الفرز الفقاعي هو O(n²) — جيد للتعلم، لكن بطيء على القوائم الكبيرة.
A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.
name is an attribute 属性 (data on the object); speak is a method 方法 (an action).
Add __str__ to control what print(obj) shows:
العربية
الفئة هي مخطط. الكائن هو شيء مبني منها (مثيل). __init__ هو البناء الذي يُعدّ كل كائن؛ self هو الكائن نفسه.
class Dog:
def __init__(self, name):
self.name = name # an attribute
def speak(self):
return self.name + " says woof"
d = Dog("Rex")
print(d.speak()) # Rex says woof
name هو سمة (بيانات على الكائن)؛ speak هي دالة (عمل).
أضف __str__ للتحكم في عرض print(obj):
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Dog named {self.name}"
print(Dog("Rex")) # Dog named Rex
الفئة هي مخطط؛ استدعاؤها تنشئ كائناً
14.2
الوراثة، التغليف، والتعدد الشكل
English
Inheritance 继承 lets a subclass 子类 reuse a superclass 父类. Use super() to call the parent; override 重写 a method to change it.
Encapsulation 封装 hides data behind methods; a leading underscore marks it private 私有.
Polymorphism 多态 means one name, many behaviours — the right speak runs for each object.
العربية
الوراثة تسمح للفئة الفرعية بإعادة استخدام الفئة الأب. استخدم super() لاستدعاء الأب؛ عدّل دالة لتغييرها.
class Animal:
def speak(self):
return "some sound"
class Cat(Animal):
def speak(self): # override
return "meow"
print(Cat().speak()) # meow
التغليف يخفي البيانات خلف الدوال؛ الشرطة السفلية الأولى تشير إلى أنها خاصة.
class Account:
def __init__(self):
self._balance = 0 # private
def deposit(self, n):
self._balance += n
def balance(self):
return self._balance
a = Account()
a.deposit(50)
print(a.balance()) # 50
التعدد الشكل يعني اسماً واحداً، سلوكيات متعددة — الدالة speak الصحيحة تعمل لكل كائن.
class Cat:
def speak(self):
return "meow"
class Cow:
def speak(self):
return "moo"
for animal in [Cat(), Cow()]:
print(animal.speak()) # meow, then moo
14.3
نماذج البرمجة
English
A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).
Common mistakes
Every method needs self as its first parameter.
__init__ sets up a new object and runs automatically when you create one.
Two objects of the same class have separate attributes; changing one does not change the other.
العربية
النمط هو أسلوب في كتابة البرامج. الكود الإجرائي هو سلسلة من الخطوات والدوال. الكود الموجه للكائنات يجمع البيانات والدوال في كائنات. الكود التصريحي يقول ماذا تريد، لا كيف (استيعاب قائمة أو SQL).
def total(nums): # procedural
t = 0
for n in nums:
t += n
return t
print(total([1, 2, 3])) # 6
print(sum([1, 2, 3])) # 6 (declarative: same result)
أخطاء شائعة
كل دالة تحتاج self كمعامل أول.
__init__ يُعدّ كائناً جديداً ويعمل تلقائياً عند إنشائه.
كائنان من نفس الفئة لديهما سمات منفصلة؛ تغيير أحدهما لا يغير الآخر.
A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.
8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:
العربية
البيت هو 0 أو 1 فردي. النظام الثنائي هو نظام العد ذو الأساس 2: قيمة كل خانة ضعف ما على يمينها (1، 2، 4، 8، …). النظام العشري (الأساس 10) هو أرقامنا العادية.
قيم خانات النظام الثنائي: 1101 تعني 8 + 4 + 1 = 13
Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.
Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.
Common mistakes
n bits store 2**n different values, from 0 up to 2**n - 1.
Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
العربية
الضغط يجعل البيانات أصغر. الضغط بدون فقدان يحفظ كل بت، لتعيد بناء الأصل بدقة. الضغط بفقدان يزيل التفاصيل — أصغر ولكن ليس دقيقاً — ويستخدم للصور والموسيقى.
ترميز المسارات المتتالية هو طريقة ضغط بدون فقدان بسيطة: تخزن المسار (التكرار) كعدد تكرارات وقيمة.
def rle(text):
out = ""
i = 0
while i < len(text):
run = 1
while i + run < len(text) and text[i + run] == text[i]:
run += 1
out += str(run) + text[i]
i += run
return out
print(rle("AAAABBBCCD")) # 4A3B2C1D
أخطاء شائعة
n بتات تخزن 2**n قيم مختلفة، من 0 حتى 2**n - 1.
الضغط بفقدان يزيل التفاصيل ولا يمكن عكسه؛ الضغط بدون فقدان يمكن عكسه بدقة.
Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.
Break a problem down, build a small part, test it, then add more.
Programmers work in teams and reuse each other's code.
العربية
الحوسبة تعني حل المشكلات باستخدام الحواسيب: إدخال، معالجة، إخراج. البرمجيات الجيدة تُبنى في دورة تصميم — تخطيط، كتابة، اختبار، تحسين — تتكرر مرات عديدة.
قسم المشكلة، بِنِ جزءاً صغيراً، اختبره، ثم أضف المزيد.
المبرمجون يعملون في فرق ويعيدون استخدام أكواد بعضهم البعض.
16.2
الإنترنت
English
The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.
Layer
Job
HTTP
request and send web pages
TCP
reliable delivery, in order
IP
addressing and routing
العربية
إنترنت هو شبكة شبكات. البيانات مقسمة إلى حزم تسافر بشكل منفصل وتُعاد تجميعها في الطرف الآخر. قواعد مشتركة تسمى بروتوكولات (مثل TCP/IP) تجعل هذا ممكنًا. إذا تعطل مسار، تأخذ الحزم طريقاً آخر — وهذا redundancy، والذي يمنح تحمل الأخطاء.
خريطة للإنترنت: كل خط هو مسار بين شبكتين
الطبقة
المهمة
HTTP
طلب وإرسال صفحات الويب
TCP
توصيل موثوق، بالترتيب
عنوان IP
والتوجيه
16.3
الحوسبة المتوازية والموزعة
English
Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.
Not everything can run in parallel: some steps must wait for an earlier result.
العربية
الكود التسلسلي ينفذ خطوة واحدة في كل مرة. الحوسبة المتوازية تنفذ عدة خطوات في آنٍ واحد على عدد من الأنوية، مما قد يوفر زيادة في السرعة. الحوسبة الموزعة توزع العمل عبر أجهزة حاسوب متعددة، مثل ساحة الحوسبة السحابية.
لا يمكن تشغيل كل شيء بالتوازي: بعض الخطوات يجب أن تنتظر نتيجة سابقة.
16.4
تأثير الحوسبة
English
Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.
Common mistakes
The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
More processor cores help only if the work can be split into parts that run at the same time.
العربية
تجلب الحوسبة فوائد وأضراراً معاً. يعني الفاصل الرقمي عدم امتلاك الجميع وصولاً متساوياً إليها. قد يحمل البرمجيات تحيزاً مستمداً من البيانات التي تتعلم منها. احترم الملكية الفكرية (التراخيص)، واحمِ البيانات الشخصية للأنظمة والخصوصية.
أخطاء شائعة
الإنترنت وشبكة المعلومات العالمية (World Wide Web) ليسا نفس الشيء: الشبكة هي خدمة واحدة تعمل فوق الإنترنت.
زيادة عدد أنوية المعالج تساعد فقط إذا كان العمل قابلاً للتقسيم إلى أجزاء تعمل في نفس الوقت.
A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.
Project: average mark
Project: count passes
Project: filter to a new list
The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.
Common mistakes
Build in small steps and test each part before moving on — do not write it all at once.
Read the whole task first, then plan the input → process → output before you code.
العربية
يجمع المشروع المصغر بين الأفكار السابقة: بيانات في قائمة، ودالة تحتوي على اختيار داخل حلقة، ومخرجات مطبوعة. هذا هو أيضاً شكل مهمة الأداء الإبداعي (AP Create Performance Task).
def count_passes(marks, pass_mark=60):
passes = 0
for m in marks: # iteration
if m >= pass_mark: # selection
passes += 1
return passes
print(count_passes([88, 50, 95, 60])) # 3
مشروع: تصفية إلى قائمة جديدة
def merit(marks):
return [m for m in marks if m >= 80]
print(merit([88, 71, 95, 60])) # [88, 95]
تطلب مهمة AP إبداع قائمة، وإجراء معلمات يستخدم فيه الاختيار والتكرار، وبعض المدخلات/المخرجات. كل مشروع أعلاه يأخذ هذا الشكل تماماً — بنِ قطعاً صغيرة، ثم ادمجها.
أخطاء شائعة
بنِ بخطوات صغيرة واختبر كل جزء قبل الانتقال إليه — لا تكتب الكود بالكامل دفعة واحدة.
اقرأ المهمة كاملة أولاً، ثم خطط للمدخلات → المعالجة → المخرجات قبل كتابة الكود.
Pick one and the site follows you — notes, papers, videos and practice all open on it. · اختر واحدًا وسيتبعك الموقع — الملاحظات، الأوراق، الفيديوهات والتدريب جميعها تفتح عليه.
Type to search notes, lessons, code, vocabulary and past-paper questions across every subject. · اكتب للبحث عن ملاحظات، دروس، أكواد، مفردات وأسئلة امتحانات سابقة عبر جميع المواد.