Iteration — loops · التكرار — الحلقات
Count-controlled loops
- Iteration means repeating steps.
- A count-controlled loop repeats a fixed number of times.
- In Python that is
for i in range(n):.
حلقات التحكم بعدد التكرارات
- التكرار (Iteration) يعني تكرار الخطوات.
- الحلقة المتحكمة بعدد التكرارات تتكرر عددًا ثابتًا من المرات.
- في Python هذا هو
for i in range(n):.
for i in range(5):
print("Hello")
Choosing the range
range(5)gives0, 1, 2, 3, 4.range(1, 6)gives1, 2, 3, 4, 5— it stops before 6.range(2, 11, 2)counts in steps of 2.
اختيار النطاق
range(5)يعطي0, 1, 2, 3, 4.range(1, 6)يعطي1, 2, 3, 4, 5— وتتوقف قبل 6.range(2, 11, 2)يعد بخطوات مقدارها 2.
for n in range(1, 6):
print(n)
Pre-condition loops: while
- A pre-condition loop tests before each pass.
- It may run zero times if the test is false at the start.
حلقات الشرط المسبق: while
- حلقة شرط مسبق تفحص قبل كل دورة.
- قد لا تعمل صفر مرة إذا كان الفحص غير صحيح في البداية.
count = 0
while count < 5:
print(count)
count = count + 1
Post-condition loops: REPEAT UNTIL
- A post-condition loop tests after each pass, so it always runs at least once.
- Python has no
repeat, so we usewhile Truewithbreak.
الحلقات ذات الشرط اللاحق: كرر حتى
- حلقة شرط لاحق تفحص بعد كل دورة، لذا فهي تعمل دائمًا مرة واحدة على الأقل.
- بايثون ليس لديها
repeat، لذا نستخدمwhile Trueمعbreak.
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Each pass changes count · كل مرور يغير العداد
A loop repeats its body; count must change so the test finally fails. · الحلقة تكرار جسمها؛ count يجب أن يتغير حتى تفشل الاختبار أخيراً.
In the exam: FOR, WHILE, REPEAT
- Pseudocode has all three loop types.
في الامتحان: FOR، WHILE، REPEAT
- الكود الوهمي يحتوي على جميع أنواع الحلقات الثلاث.
FOR I ← 1 TO 5
OUTPUT I
NEXT I
Common mistakes
- A
forloop repeats a known number of times; awhilerepeats until something changes. range(n)runs0ton - 1.- Change the condition inside a
while, or it never ends.
أخطاء شائعة
- حلقة
forتكرر عددًا معروفًا من المرات؛ حلقةwhileتكرر حتى يتغير شيء ما. range(n)تشغل من0إلىn - 1.- غيّر الشرط داخل حلقة
while، أو لن تنتهي أبدًا.
Now you try
- Pick the loop that fits each task.
- Press Check answer to test your code.
الآن جرب بنفسك
- اختر الحلقة التي تناسب كل مهمة.
- اضغط على تحقق من الإجابة لاختبار الكود الخاص بك.
Use a for loop to print the numbers 1 to 5, one on each line. · استخدم حلقة for لطباعة الأرقام من 1 إلى 5، واحد على كل سطر.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a loop to add up the numbers 1 to 10, then print the total (it is 55). · استخدم حلقة لجمع الأرقام من 1 إلى 10، ثم اطبع المجموع الكلي (وهو 55).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Read a whole number n, then count down from n to 1, one per line. For input 3, print 3, 2, 1. · اقرأ عددًا صحيحًا n، ثم عدّ تنازليًا من n إلى 1، واحدًا في كل سطر. بالنسبة للمدخلات 3، اطبع 3، 2، 1.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.