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

חזרה למפגשBack
PythonPython

לולאותLoops

מפגש 6: while, for, range, break ו-continue, ולולאת תפריט.Session 6: while, for, range, break and continue, and a menu loop.

מה נעשה היוםToday's plan

  • whilewhile
  • forfor
  • rangerange
  • צובריםAccumulators
  • break/continuebreak/continue
  • תפריטMenu loop
נושאTopic 1

whilewhile

while: כל עודwhile: as long as

  • חוזר כל עוד התנאי TrueRepeats while the condition is True
  • משהו בתוך הלולאה חייב לשנות את התנאיSomething inside must change the condition
  • אחרת: לולאה אינסופיתOtherwise: an infinite loop

אנלוגיה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.
נושאTopic 2

forfor

for: על כל פריטfor: for each item

  • for x in רצף:for x in sequence:
  • עובד על מחרוזות, רשימות ו-rangeWorks on strings, lists and range
  • המשתנה מקבל פריט חדש בכל סיבובThe variable gets a new item each pass
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

python
for letter in "Dune":
    print(letter)
for book in ["Dune", "Emma", "Ulysses"]:
    print(f"📚 {book}")

    forfor

    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

    אנלוגיה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

    for_demo.py
    for letter "Dune":
        print(letter)
    מה Python עונהWhat Python says
    SyntaxError: invalid syntax
    SyntaxError: התבנית היא for <משתנה> in <רצף>:.SyntaxError: the pattern is for <variable> in <sequence>:.
    נושאTopic 3

    rangerange

    range: לספורrange: counting

    • range(5) → 0..4range(5) → 0..4
    • range(1, 6) → 1..5range(1, 6) → 1..5
    • range(10, 0, -2) סופר לאחורrange(10, 0, -2) counts down
    שאלה לכיתהQuestion for the class

    מה ידפיס הקוד?What will this print?

    python
    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()

      rangerange

      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 

      אנלוגיה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_demo.py
      for i in range(2.5):
          print(i)
      מה Python עונהWhat Python says
      TypeError: 'float' object cannot be interpreted as an integer
      TypeError: 'float' object cannot be interpreted as an integer: range עובד רק עם int.TypeError: 'float' object cannot be interpreted as an integer: range takes int only.
      נושאTopic 4

      צובריםAccumulators

      צוברים: סכום, מונה, מקסימוםAccumulators: sum, count, max

      • מתחילים ב-0 לפני הלולאהStart at 0 before the loop
      • מוסיפים בכל סיבובAdd on every pass
      • משתמשים בתוצאה אחרי הלולאהUse the result after the loop

      אנלוגיה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.
      נושאTopic 5

      break/continuebreak/continue

      break ו-continuebreak and continue

      • break יוצא מהלולאה מידbreak leaves the loop at once
      • continue מדלג לסיבוב הבאcontinue skips to the next pass
      • while True + break לתפריטיםwhile True + break for menus
      שאלה לכיתהQuestion for the class

      מה ידפיס הקוד?What will this print?

      python
      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)

        break/continuebreak/continue

        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

        אנלוגיהAnalogy

        continue הוא כמו לדלג על שיר בפלייליסט. break הוא לכבות את הנגן.continue is skipping a song in a playlist. break is switching the player off.

        טעות נפוצהCommon mistake

        break_demo.py
        x = 5
        if x > 3:
            break
        מה Python עונהWhat Python says
        SyntaxError: 'break' outside loop
        SyntaxError: 'break' outside loop: break שייך רק לתוך for או while.SyntaxError: 'break' outside loop: break only belongs inside a for or while.
        נושאTopic 6

        תפריטMenu loop

        לולאת תפריטA menu loop

        • while True: מציג תפריטwhile True: shows a menu
        • כל בחירה = if/elifEach choice = if/elif
        • בחירת יציאה = breakThe quit choice = break

        אנלוגיהAnalogy

        תפריט בלולאה הוא כמו מלצר שחוזר לשולחן שוב ושוב עד שמבקשים חשבון.A menu loop is like a waiter who keeps coming back to the table until you ask for the bill.

        חוזר כל עוד התנאי TrueRepeats while the condition is True

        משהו בתוך הלולאה חייב לשנות את התנאיSomething inside must change the condition

        אחרת: לולאה אינסופיתOtherwise: an infinite loop

        for x in רצף:for x in sequence:

        עובד על מחרוזות, רשימות ו-rangeWorks on strings, lists and range

        המשתנה מקבל פריט חדש בכל סיבובThe variable gets a new item each pass

        range(5) → 0..4range(5) → 0..4

        range(1, 6) → 1..5range(1, 6) → 1..5

        range(10, 0, -2) סופר לאחורrange(10, 0, -2) counts down

        מה למדנוWhat we learned

        • חוזר כל עוד התנאי TrueRepeats while the condition is True
        • for x in רצף:for x in sequence:
        • range(5) → 0..4range(5) → 0..4
        • מתחילים ב-0 לפני הלולאהStart at 0 before the loop
        • break יוצא מהלולאה מידbreak leaves the loop at once
        • while True: מציג תפריטwhile True: shows a menu

        עכשיו לתרגולNow, practice

        5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
        הערות מרצהSpeaker notes

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