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):.
לולאות המופעלות על ספירה
- איטרציה פירושה חזרה על צעדים.
- לולאה מופעלת על ספירה חוזרת מספר פעמים קבוע.
- בפיתון זה נכתב כ
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 UNTIL
- לולאת תנאי-אחרון בודקת את התנאי לאחר כל מעבר, ולכן היא תתבצע למינימום פעם אחת.
- ל-Python אין
repeat, לכן אנו משתמשים בwhile Trueעםbreak.
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Each pass changes count · כל מעבר משנה את 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, או she-ta never ends (never ends).
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. · לחץ על הרץ כדי לראות את התוצא כאן.