נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
6
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

לולאות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.

while_demo.py
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!")
פלטOutput
יום 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
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סימולציהSimulationהלולאה בודקת את התנאי בכל סיבובThe loop checks its condition every pass

מה קורה עכשיוWhat happens now

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

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.

טעות נפוצהCommon mistake

לולאה אינסופית: שוכחים לעדכן את המשתנה. כאן הדפדפן עוצר אחרי כמה שניות, ובטרמינל עוצרים עם 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.

while_demo.py
n = 3
steps = 0
while n > 0:
    steps += 1
    if steps > 1000:
        raise RuntimeError("n never changes: infinite loop")
print(n)
מה Python עונהWhat Python says
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 loop
בעברית פשוטה: In plain words: n אף פעם לא קטן, אז התנאי תמיד True. בתוך הלולאה חייב להיות n -= 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_demo.py
for letter in "Dune":
    print(letter)
for book in ["Dune", "Emma", "Ulysses"]:
    print(f"📚 {book}")
פלטOutput
D
u
n
e
📚 Dune
📚 Emma
📚 Ulysses
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

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.

טעות נפוצהCommon mistake

שוכחים את in.

Forgetting in.

for_demo.py
for letter "Dune":
    print(letter)
מה Python עונהWhat Python says
  File "/Users/you/python-course/for_demo.py", line 1
    for letter "Dune":
               ^^^^^^
SyntaxError: invalid syntax
בעברית פשוטה: In plain words: SyntaxError: התבנית היא for <משתנה> in <רצף>:.SyntaxError: the pattern is for <variable> in <sequence>:.

לולאה עם range שסופר אחורה, צעד של מינוס 1.

A loop with range counting down, a step of minus 1.

עוד דוגמה: ספירה לאחורOne more: a countdown
example.py
for n in range(5, 0, -1):
    print(n)
print("Lift off!")
פלטOutput
5
4
3
2
1
Lift off!
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

range_demo.py
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()
פלטOutput
0 1 2 
1 2 3 4 5 
10 7 4 1 
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

range הוא כמו מונה צעדים שמכוון מראש: "מ-1, עד לפני 6, בקפיצות של 1".

range is like a pre-set step counter: "from 1, up to (not incl.) 6, in steps of 1".

טעות נפוצהCommon mistake

מעבירים ל-range מספר עשרוני.

Passing a decimal to range.

range_demo.py
for i in range(2.5):
    print(i)
מה Python עונהWhat Python says
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 integer
בעברית פשוטה: In plain words: TypeError: '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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

acc.py
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)
פלטOutput
1824 1 1036
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

צובר הוא כמו קופה רושמת: מתחילה באפס בבוקר, וכל קנייה מוסיפה. בערב מסתכלים על הסכום.

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.

טעות נפוצהCommon mistake

מאפסים את הצובר בתוך הלולאה, ולכן הוא אף פעם לא מצטבר. כאן הקוד מוסיף בדיקה שמגלה את זה.

Resetting the accumulator inside the loop, so it never accumulates. Here the code adds a check that catches it.

acc.py
total = 0
for p in [10, 20, 30]:
    total = 0
    total += p
assert total == 60, f"total is {total}, not 60"
מה Python עונהWhat Python says
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 60
בעברית פשוטה: In plain words: AssertionError: total = 0 צריך להיות לפני הלולאה, פעם אחת.AssertionError: total = 0 belongs before the loop, once.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

צובר: מתחילים מאפס ומוסיפים בכל סיבוב.

An accumulator: start at zero and add each round.

עוד דוגמה: כמה כוכבים אספתיOne more: how many stars I collected
example.py
stars = [3, 0, 5, 2]
total = 0
for s in stars:
    total += s
print("Stars:", total)
פלטOutput
Stars: 10
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

break_demo.py
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)
פלטOutput
96
412
נתון שגוי, עוצרים
96
412
bad data, stopping
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

continue הוא כמו לדלג על שיר בפלייליסט. break הוא לכבות את הנגן.

continue is skipping a song in a playlist. break is switching the player off.

טעות נפוצהCommon mistake

משתמשים ב-break מחוץ ללולאה.

Using break outside a loop.

break_demo.py
x = 5
if x > 3:
    break
מה Python עונהWhat Python says
  File "/Users/you/python-course/break_demo.py", line 3
    break
    ^^^^^
SyntaxError: 'break' outside loop
בעברית פשוטה: In plain words: SyntaxError: '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.

נבנה על ידיBuilt by Ariel Yohimovich