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

חזרה למפגשBack
PythonPython

תנאיםConditions

מפגש 5: if, elif, else, השוואות, and/or/not ואמת/שקר.Session 5: if, elif, else, comparisons, and/or/not and truthiness.

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

  • ifif
  • elif ו-elseelif and else
  • השוואותComparisons
  • and/or/notand/or/not
  • truthinessTruthiness
  • קינוןNesting
נושאTopic 1

ifif

if: לבצע רק אםif: run only when

  • if תנאי: ואז בלוק מוזחif condition: then an indented block
  • הבלוק רץ רק אם התנאי TrueThe block runs only if the condition is True
  • נקודתיים + 4 רווחיםColon + 4 spaces
שאלה לכיתהQuestion for the class

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

python
pages = int(input("כמה עמודים? "))
if pages > 500:
    print("ספר עבה!")
    print("כדאי לפנות סופ״ש")
print("בהצלחה בקריאה")
pages = int(input("How many pages? "))
if pages > 500:
    print("A thick book!")
    print("Clear a weekend")
print("Happy reading")

    ifif

    if_demo.py
    pages = int(input("כמה עמודים? "))
    if pages > 500:
        print("ספר עבה!")
        print("כדאי לפנות סופ״ש")
    print("בהצלחה בקריאה")
    pages = int(input("How many pages? "))
    if pages > 500:
        print("A thick book!")
        print("Clear a weekend")
    print("Happy reading")
    פלטOutput
    כמה עמודים? 640
    ספר עבה!
    כדאי לפנות סופ״ש
    בהצלחה בקריאה
    How many pages? 640
    A thick book!
    Clear a weekend
    Happy reading

    אנלוגיהAnalogy

    if הוא כמו שומר בכניסה למועדון: בודק תנאי (גיל), ורק מי שעומד בו נכנס. השאר ממשיכים הלאה ברחוב.if is like a bouncer at a club door: checks a condition (age) and only those who pass go in. Everyone else carries on down the street.

    טעות נפוצהCommon mistake

    if_demo.py
    pages = 640
    if pages > 500
        print("Thick")
    מה Python עונהWhat Python says
    SyntaxError: expected ':'
    SyntaxError: expected ':': כל if, elif, else נגמרים בנקודתיים.SyntaxError: expected ':': every if, elif, else ends with a colon.
    נושאTopic 2

    elif ו-elseelif and else

    else ו-elif: כמה מסלוליםelse and elif: several paths

    • else כשאף תנאי לא התקייםelse when no condition held
    • elif בודק תנאי נוסףelif checks another condition
    • רק מסלול אחד רץOnly one path runs
    שאלה לכיתהQuestion for the class

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

    python
    score = int(input("ציון: "))
    if score >= 90:
        print("A")
    elif score >= 80:
        print("B")
    elif score >= 60:
        print("C")
    else:
        print("נכשל")
    score = int(input("Score: "))
    if score >= 90:
        print("A")
    elif score >= 80:
        print("B")
    elif score >= 60:
        print("C")
    else:
        print("Fail")

      elif ו-elseelif and else

      grade.py
      score = int(input("ציון: "))
      if score >= 90:
          print("A")
      elif score >= 80:
          print("B")
      elif score >= 60:
          print("C")
      else:
          print("נכשל")
      score = int(input("Score: "))
      if score >= 90:
          print("A")
      elif score >= 80:
          print("B")
      elif score >= 60:
          print("C")
      else:
          print("Fail")
      פלטOutput
      ציון: 84
      B
      Score: 84
      B

      אנלוגיהAnalogy

      elif הוא כמו מכונת מיון מטבעות: המטבע נופל דרך חורים מהגדול לקטן, ונעצר בחור הראשון שהוא נכנס אליו.elif is like a coin sorter: the coin drops past holes from largest to smallest and stops at the first one it fits.

      טעות נפוצהCommon mistake

      grade.py
      x = 5
      if x > 10:
          print("big")
      else x > 3:
          print("medium")
      מה Python עונהWhat Python says
      SyntaxError: expected ':'
      SyntaxError: ל-else אין תנאי. תנאי נוסף כותבים עם elif.SyntaxError: else takes no condition. Another condition uses elif.
      נושאTopic 3

      השוואותComparisons

      השוואותComparisons

      • == != < > <= >=== != < > <= >=
      • = משייך, == משווה= assigns, == compares
      • אפשר לשרשר: 1 < x < 10You can chain: 1 < x < 10
      שאלה לכיתהQuestion for the class

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

      python
      age = 16
      print(age == 16, age != 16)
      print(13 <= age < 18)
      print("apple" < "banana")
      print("Zebra" < "apple")

        השוואותComparisons

        compare.py
        age = 16
        print(age == 16, age != 16)
        print(13 <= age < 18)
        print("apple" < "banana")
        print("Zebra" < "apple")
        פלטOutput
        True False
        True
        True
        True

        אנלוגיהAnalogy

        = הוא "שים את זה בקופסה". == הוא "האם מה שבקופסה זהה לזה?". פעולה מול שאלה.= is "put this in the box". == is "is what's in the box the same as this?". An action versus a question.

        טעות נפוצהCommon mistake

        compare.py
        age = 16
        if age = 16:
            print("16!")
        מה Python עונהWhat Python says
        SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
        SyntaxError: Python אפילו שואלת אם התכוונתם ל-==. בתנאי משווים עם ==.SyntaxError: Python even asks whether you meant ==. Conditions compare with ==.
        נושאTopic 4

        and/or/notand/or/not

        and, or, notand, or, not

        • and: שניהם נכוניםand: both true
        • or: לפחות אחדor: at least one
        • not: הופךnot: flips

        אנלוגיהAnalogy

        and הוא כמו כספת עם שני מפתחות: צריך את שניהם. or הוא כמו בית עם שתי דלתות: מספיקה אחת.and is like a safe with two keys: you need both. or is like a house with two doors: one is enough.

        טעות נפוצהCommon mistake

        logic.py
        x = 5
        if x == 1 or x = 2:
            print("one or two")
        מה Python עונהWhat Python says
        SyntaxError: invalid syntax
        SyntaxError: כל צד צריך תנאי שלם עם ==: x == 1 or x == 2, או x in (1, 2).SyntaxError: each side needs a full condition with ==: x == 1 or x == 2, or x in (1, 2).
        נושאTopic 5

        truthinessTruthiness

        truthy ו-falsyTruthy and falsy

        • 0, "", None הם falsy0, "", None are falsy
        • if name: = "אם יש שם"if name: = "if there is a name"
        • כל השאר truthyEverything else is truthy
        שאלה לכיתהQuestion for the class

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

        python
        name = input("שם (אפשר ריק): ")
        if name:
            print(f"שלום {name}")
        else:
            print("שלום, אורח/ת")
        name = input("Name (can be empty): ")
        if name:
            print(f"Hi {name}")
        else:
            print("Hi, guest")

          truthinessTruthiness

          truthy.py
          name = input("שם (אפשר ריק): ")
          if name:
              print(f"שלום {name}")
          else:
              print("שלום, אורח/ת")
          name = input("Name (can be empty): ")
          if name:
              print(f"Hi {name}")
          else:
              print("Hi, guest")
          פלטOutput
          שם (אפשר ריק): 
          שלום, אורח/ת
          Name (can be empty): 
          Hi, guest

          אנלוגיהAnalogy

          זה כמו לבדוק אם יש משהו בארנק: לא צריך לספור כמה, רק אם הוא ריק או לא.It's like checking whether there's anything in your wallet: you don't count, you just check if it's empty.
          נושאTopic 6

          קינוןNesting

          קינון והזחהNesting and indentation

          • if בתוך if = עוד רמת הזחהif inside if = another indent level
          • הזחה שגויה = שגיאה או באגWrong indentation = an error or a bug
          • לעתים and עדיף על קינוןOften and beats nesting
          שאלה לכיתהQuestion for the class

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

          python
          member = True
          books = 3
          if member:
              if books < 5:
                  print("אפשר לשאול עוד ספר")
              else:
                  print("הגעת למקסימום")
          else:
              print("צריך להירשם")
          member = True
          books = 3
          if member:
              if books < 5:
                  print("You can borrow another")
              else:
                  print("You reached the limit")
          else:
              print("Please sign up")

            קינוןNesting

            nested.py
            member = True
            books = 3
            if member:
                if books < 5:
                    print("אפשר לשאול עוד ספר")
                else:
                    print("הגעת למקסימום")
            else:
                print("צריך להירשם")
            member = True
            books = 3
            if member:
                if books < 5:
                    print("You can borrow another")
                else:
                    print("You reached the limit")
            else:
                print("Please sign up")
            פלטOutput
            אפשר לשאול עוד ספר
            You can borrow another

            אנלוגיהAnalogy

            הזחה היא כמו תיקיות בתוך תיקיות: מה שבפנים שייך לתיקייה שעוטפת אותו.Indentation is like folders inside folders: whatever is inside belongs to the folder around it.

            טעות נפוצהCommon mistake

            nested.py
            pages = 600
            if pages > 500:
            print("thick")
            מה Python עונהWhat Python says
            IndentationError: expected an indented block after 'if' statement on line 2
            IndentationError: expected an indented block: מזיחים 4 רווחים (או Tab ב-VS Code).IndentationError: expected an indented block: indent 4 spaces (or Tab in VS Code).

            if תנאי: ואז בלוק מוזחif condition: then an indented block

            הבלוק רץ רק אם התנאי TrueThe block runs only if the condition is True

            נקודתיים + 4 רווחיםColon + 4 spaces

            מה למדנוWhat we learned

            • if תנאי: ואז בלוק מוזחif condition: then an indented block
            • else כשאף תנאי לא התקייםelse when no condition held
            • == != < > <= >=== != < > <= >=
            • and: שניהם נכוניםand: both true
            • 0, "", None הם falsy0, "", None are falsy
            • if בתוך if = עוד רמת הזחהif inside if = another indent level

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

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

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