לולאותLoops
while, for, range, break ו-continue, ולולאת תפריט.
while, for, range, break and continue, and a menu loop.
01while: כל עודwhile: as long as
לולאת while מריצה את הבלוק שוב ושוב כל עוד התנאי נכון. בכל סיבוב התנאי נבדק מחדש. חובה שמשהו בתוך הלולאה יקרב אותה לסוף.
A while loop runs its block again and again as long as the condition is true. The condition is rechecked on every iteration. Something inside must move the loop toward its end.
pages_left = 50
day = 0
while pages_left > 0:
day += 1
pages_left -= 20
print(f"יום {day}: נשארו {max(pages_left, 0)}")
print("סיימתי!")pages_left = 50
day = 0
while pages_left > 0:
day += 1
pages_left -= 20
print(f"Day {day}: left {max(pages_left, 0)}")
print("Finished!")יום 1: נשארו 30 יום 2: נשארו 10 יום 3: נשארו 0 סיימתי!
Day 1: left 30 Day 2: left 10 Day 3: left 0 Finished!
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
מסך הפלטOutput screen
while הוא כמו לאכול מרק "כל עוד יש בצלחת": כל כף מקרבת לסוף. אם הכף הייתה ריקה, היינו אוכלים לנצח.
while is like eating soup "as long as there's some in the bowl": each spoonful gets you closer to the end. With an empty spoon you'd eat forever.
לולאה אינסופית: שוכחים לעדכן את המשתנה. כאן הדפדפן עוצר אחרי כמה שניות, ובטרמינל עוצרים עם Ctrl+C. הדוגמה עוצרת בכוונה עם שגיאה כדי להראות את הרעיון.
An infinite loop: forgetting to update the variable. The browser stops it after a few seconds; in a terminal press Ctrl+C. This example deliberately stops with an error to show the idea.
n = 3
steps = 0
while n > 0:
steps += 1
if steps > 1000:
raise RuntimeError("n never changes: infinite loop")
print(n)Traceback (most recent call last):
File "/Users/you/python-course/while_demo.py", line 6, in <module>
raise RuntimeError("n never changes: infinite loop")
RuntimeError: n never changes: infinite loopn -= 1 או משהו דומה.n never shrinks, so the condition is always True. The loop needs n -= 1 or similar.02for: על כל פריטfor: for each item
for עוברת על הפריטים של רצף, אחד אחרי השני. המשתנה שאחרי for מקבל בכל סיבוב את הפריט הבא. כשהפריטים נגמרים, הלולאה נגמרת לבד: אין סכנה ללולאה אינסופית.
for walks through a sequence's items one by one. The variable after for gets the next item each pass. When the items run out the loop ends by itself: no risk of an infinite loop.
for letter in "Dune":
print(letter)
for book in ["Dune", "Emma", "Ulysses"]:
print(f"📚 {book}")D u n e 📚 Dune 📚 Emma 📚 Ulysses
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
for הוא כמו מורה שעובר בין השולחנות ובודק כל מחברת בתורה. הוא לא צריך לספור: כשהשולחנות נגמרים, הוא סיים.
for is like a teacher walking past every desk to check each notebook in turn. No counting needed: when the desks run out, it's done.
שוכחים את in.
Forgetting in.
for letter "Dune":
print(letter) File "/Users/you/python-course/for_demo.py", line 1
for letter "Dune":
^^^^^^
SyntaxError: invalid syntaxSyntaxError: התבנית היא for <משתנה> in <רצף>:.SyntaxError: the pattern is for <variable> in <sequence>:.לולאה עם range שסופר אחורה, צעד של מינוס 1.
A loop with range counting down, a step of minus 1.
for n in range(5, 0, -1):
print(n)
print("Lift off!")5 4 3 2 1 Lift off!
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03range: לספורrange: counting
range יוצר רצף מספרים בלי לשמור את כולם בזיכרון. כמו בחיתוך: ההתחלה נכללת, הסוף לא. צעד שלישי קובע בכמה לקפוץ, וגם שלילי מותר.
range makes a sequence of numbers without storing them all. Like slicing: the start is included, the end isn't. A third step sets how far to jump, and it may be negative.
for i in range(3):
print(i, end=" ")
print()
for day in range(1, 6):
print(day, end=" ")
print()
for n in range(10, 0, -3):
print(n, end=" ")
print()0 1 2 1 2 3 4 5 10 7 4 1
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
range הוא כמו מונה צעדים שמכוון מראש: "מ-1, עד לפני 6, בקפיצות של 1".
range is like a pre-set step counter: "from 1, up to (not incl.) 6, in steps of 1".
מעבירים ל-range מספר עשרוני.
Passing a decimal to range.
for i in range(2.5):
print(i)Traceback (most recent call last):
File "/Users/you/python-course/range_demo.py", line 1, in <module>
for i in range(2.5):
~~~~~^^^^^
TypeError: 'float' object cannot be interpreted as an integerTypeError: 'float' object cannot be interpreted as an integer: range עובד רק עם int.TypeError: 'float' object cannot be interpreted as an integer: range takes int only.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04צוברים: סכום, מונה, מקסימוםAccumulators: sum, count, max
צובר הוא משתנה שמתחיל לפני הלולאה (בדרך כלל 0) ומשתנה בכל סיבוב. ככה סוכמים, סופרים, או מוצאים את הגדול ביותר.
An accumulator is a variable set up before the loop (usually 0) that changes on every pass. That's how you sum, count, or find the largest.
pages = [412, 96, 1036, 280]
total = 0
long_books = 0
biggest = pages[0]
for p in pages:
total += p
if p > 500:
long_books += 1
if p > biggest:
biggest = p
print(total, long_books, biggest)1824 1 1036
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צובר הוא כמו קופה רושמת: מתחילה באפס בבוקר, וכל קנייה מוסיפה. בערב מסתכלים על הסכום.
An accumulator is like a till: it starts at zero in the morning and every sale adds to it. In the evening you read the total.
מאפסים את הצובר בתוך הלולאה, ולכן הוא אף פעם לא מצטבר. כאן הקוד מוסיף בדיקה שמגלה את זה.
Resetting the accumulator inside the loop, so it never accumulates. Here the code adds a check that catches it.
total = 0
for p in [10, 20, 30]:
total = 0
total += p
assert total == 60, f"total is {total}, not 60"Traceback (most recent call last):
File "/Users/you/python-course/acc.py", line 5, in <module>
assert total == 60, f"total is {total}, not 60"
^^^^^^^^^^^
AssertionError: total is 30, not 60AssertionError: total = 0 צריך להיות לפני הלולאה, פעם אחת.AssertionError: total = 0 belongs before the loop, once.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צובר: מתחילים מאפס ומוסיפים בכל סיבוב.
An accumulator: start at zero and add each round.
stars = [3, 0, 5, 2]
total = 0
for s in stars:
total += s
print("Stars:", total)Stars: 10
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05break ו-continuebreak and continue
break עוצר את הלולאה ויוצא ממנה. continue מדלג על שאר הסיבוב הנוכחי ועובר לבא. הצירוף while True עם break שימושי ללולאה שרצה עד שהמשתמש מבקש לצאת.
break stops the loop and leaves it. continue skips the rest of the current pass and moves to the next. while True with break is handy for a loop that runs until the user asks to quit.
for p in [96, 0, 412, -5, 280]:
if p < 0:
print("נתון שגוי, עוצרים")
break
if p == 0:
continue
print(p)for p in [96, 0, 412, -5, 280]:
if p < 0:
print("bad data, stopping")
break
if p == 0:
continue
print(p)96 412 נתון שגוי, עוצרים
96 412 bad data, stopping
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
continue הוא כמו לדלג על שיר בפלייליסט. break הוא לכבות את הנגן.
continue is skipping a song in a playlist. break is switching the player off.
משתמשים ב-break מחוץ ללולאה.
Using break outside a loop.
x = 5
if x > 3:
break File "/Users/you/python-course/break_demo.py", line 3
break
^^^^^
SyntaxError: 'break' outside loopSyntaxError: 'break' outside loop: break שייך רק לתוך for או while.SyntaxError: 'break' outside loop: break only belongs inside a for or while.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.