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

חזרה למפגשBack
PythonPython

פונקציותFunctions

מפגש 9: def, פרמטרים, ערכי ברירת מחדל ולמה מפרקים קוד.Session 9: def, parameters, default values and why we split code.

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

  • defdef
  • פרמטריםParameters
  • ברירות מחדלDefaults
  • returnreturn
  • docstringDocstrings
  • פירוק לפונקציותDecomposition
נושאTopic 1

defdef

פונקציה: קוד עם שםA function: code with a name

  • def name(): + בלוק מוזחdef name(): + an indented block
  • ההגדרה לא מריצה כלוםDefining runs nothing
  • הקריאה name() מריצהThe call name() runs it
שאלה לכיתהQuestion for the class

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

python
def banner():
    print("=" * 24)
    print("📚 מדף: הספרייה שלי")
    print("=" * 24)

banner()
print("...תוכן...")
banner()
def banner():
    print("=" * 24)
    print("📚 Shelf: my library")
    print("=" * 24)

banner()
print("...content...")
banner()

    defdef

    banner.py
    def banner():
        print("=" * 24)
        print("📚 מדף: הספרייה שלי")
        print("=" * 24)
    
    banner()
    print("...תוכן...")
    banner()
    def banner():
        print("=" * 24)
        print("📚 Shelf: my library")
        print("=" * 24)
    
    banner()
    print("...content...")
    banner()
    פלטOutput
    ========================
    📚 מדף: הספרייה שלי
    ========================
    ...תוכן...
    ========================
    📚 מדף: הספרייה שלי
    ========================
    ========================
    📚 Shelf: my library
    ========================
    ...content...
    ========================
    📚 Shelf: my library
    ========================

    אנלוגיהAnalogy

    פונקציה היא כמו מתכון שכתבתם פעם אחת בפנקס. כל פעם שרוצים עוגה, לא כותבים את המתכון מחדש: רק אומרים "תכין את העוגה".A function is like a recipe written once in a notebook. Each time you want the cake you don't rewrite the recipe: you just say "make the cake".

    טעות נפוצהCommon mistake

    banner.py
    banner()
    def banner():
        print("===")
    מה Python עונהWhat Python says
    NameError: name 'banner' is not defined
    NameError: Python קוראת מלמעלה למטה, ובשורה 1 banner עוד לא קיימת. מגדירים למעלה, קוראים למטה.NameError: Python reads top down, and on line 1 banner doesn't exist yet. Define above, call below.
    נושאTopic 2

    פרמטריםParameters

    פרמטרים: מידע שנכנסParameters: data going in

    • def greet(name):def greet(name):
    • הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter
    • כמה פרמטרים מופרדים בפסיקSeveral parameters, comma separated

    אנלוגיהAnalogy

    פרמטר הוא כמו חור בטופס: "שם: ____". כל פעם שממלאים את הטופס (קוראים לפונקציה), כותבים בחור ערך אחר.A parameter is like a blank on a form: "Name: ____". Each time you fill in the form (call the function), you write a different value in the blank.

    טעות נפוצהCommon mistake

    card.py
    def book_card(title, author):
        print(title, author)
    
    book_card("Dune")
    מה Python עונהWhat Python says
    TypeError: book_card() missing 1 required positional argument: 'author'
    TypeError: book_card() missing 1 required positional argument: 'author': מעבירים ערך לכל פרמטר, או נותנים לו ברירת מחדל.TypeError: book_card() missing 1 required positional argument: 'author': pass a value for every parameter, or give it a default.
    נושאTopic 3

    ברירות מחדלDefaults

    ברירת מחדל וארגומנטים לפי שםDefaults and keyword arguments

    • def f(x, unit="cm"):def f(x, unit="cm"):
    • קריאה לפי שם: f(5, unit="m")Keyword call: f(5, unit="m")
    • פרמטרים עם ברירת מחדל באים בסוףDefaulted parameters go last

    אנלוגיהAnalogy

    ברירת מחדל היא כמו הזמנת קפה "רגיל": אם לא אמרתם אחרת, תקבלו עם חלב. מי שרוצה שחור, אומר במפורש.A default is like ordering a "regular" coffee: unless you say otherwise you get milk. Want it black? Say so explicitly.

    טעות נפוצהCommon mistake

    defaults.py
    def reading_time(per_hour=40, pages):
        return pages / per_hour
    מה Python עונהWhat Python says
    SyntaxError: parameter without a default follows parameter with a default
    SyntaxError: parameter without a default follows parameter with a default: פרמטרים חובה קודם, אופציונליים אחר כך.SyntaxError: parameter without a default follows parameter with a default: required first, optional after.
    נושאTopic 4

    returnreturn

    return: מידע שיוצאreturn: data coming out

    • return x מחזיר ערך לקוראreturn x hands a value back
    • אחרי return הפונקציה נגמרתAfter return the function ends
    • בלי return מקבלים NoneWithout return you get None
    שאלה לכיתהQuestion for the class

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

    python
    def percent(read, total):
        return round(read / total * 100)
    
    done = percent(103, 412)
    print(f"{done}%")
    if percent(400, 412) > 90:
        print("כמעט סיימת!")
    def percent(read, total):
        return round(read / total * 100)
    
    done = percent(103, 412)
    print(f"{done}%")
    if percent(400, 412) > 90:
        print("Almost done!")

      returnreturn

      return.py
      def percent(read, total):
          return round(read / total * 100)
      
      done = percent(103, 412)
      print(f"{done}%")
      if percent(400, 412) > 90:
          print("כמעט סיימת!")
      def percent(read, total):
          return round(read / total * 100)
      
      done = percent(103, 412)
      print(f"{done}%")
      if percent(400, 412) > 90:
          print("Almost done!")
      פלטOutput
      25%
      כמעט סיימת!
      25%
      Almost done!

      אנלוגיהAnalogy

      פונקציה עם return היא כמו מכונת מיץ: מכניסים תפוזים (ארגומנטים), ומקבלים כוס מיץ (ערך) שאפשר לשתות, לשמור או לתת למישהו.A function with return is like a juicer: oranges go in (arguments) and a glass of juice comes out (a value) that you can drink, keep or hand to someone.

      טעות נפוצהCommon mistake

      return.py
      def double(x):
          print(x * 2)
      
      result = double(5) + 1
      מה Python עונהWhat Python says
      TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
      TypeError: unsupported operand type(s) for +: 'NoneType' and 'int': הפונקציה מדפיסה אבל לא מחזירה, ולכן התוצאה None. מחליפים ל-return x * 2.TypeError: unsupported operand type(s) for +: 'NoneType' and 'int': the function prints but doesn't return, so the result is None. Change it to return x * 2.
      נושאTopic 5

      docstringDocstrings

      docstring ושמות טוביםDocstrings and good names

      • שם פונקציה = פועל: add_bookFunction name = a verb: add_book
      • docstring בשורה הראשונהA docstring on the first line
      • help(f) מציג אותוhelp(f) shows it

      אנלוגיהAnalogy

      docstring היא כמו התווית על קופסת שימורים: לא צריך לפתוח את הקופסה כדי לדעת מה בפנים.A docstring is like the label on a tin: you don't need to open it to know what's inside.

      טעות נפוצהCommon mistake

      doc.py
      def pages_left(total, read)
          return total - read
      מה Python עונהWhat Python says
      SyntaxError: expected ':'
      SyntaxError: expected ':': כמו if, גם def נגמר בנקודתיים.SyntaxError: expected ':': like if, def ends with a colon.
      נושאTopic 6

      פירוק לפונקציותDecomposition

      לפרק תוכנית לפונקציותSplitting a program into functions

      • כל פונקציה עושה דבר אחדEach function does one thing
      • DRY: לא חוזרים על קודDRY: don't repeat code
      • פונקציה ראשית main() מחברת הכולA main() function ties it together

      אנלוגיהAnalogy

      פירוק לפונקציות הוא כמו מטבח של מסעדה: יש תחנת סלטים, תחנת גריל ותחנת קינוחים. השף הראשי (main) רק מתאם ביניהן.Decomposition is like a restaurant kitchen: a salad station, a grill station, a dessert station. The head chef (main) just coordinates.

      טעות נפוצהCommon mistake

      split.py
      def total():
          return 412
      
      print(total + 1)
      מה Python עונהWhat Python says
      TypeError: unsupported operand type(s) for +: 'function' and 'int'
      TypeError: unsupported operand type(s) for +: 'function' and 'int': בלי () הפונקציה לא רצה. כותבים total() + 1.TypeError: unsupported operand type(s) for +: 'function' and 'int': without () the function doesn't run. Write total() + 1.

      def name(): + בלוק מוזחdef name(): + an indented block

      ההגדרה לא מריצה כלוםDefining runs nothing

      הקריאה name() מריצהThe call name() runs it

      def greet(name):def greet(name):

      הערך בקריאה מגיע לפרמטרThe call's value lands in the parameter

      כמה פרמטרים מופרדים בפסיקSeveral parameters, comma separated

      def f(x, unit="cm"):def f(x, unit="cm"):

      קריאה לפי שם: f(5, unit="m")Keyword call: f(5, unit="m")

      מה למדנוWhat we learned

      • def name(): + בלוק מוזחdef name(): + an indented block
      • def greet(name):def greet(name):
      • def f(x, unit="cm"):def f(x, unit="cm"):
      • return x מחזיר ערך לקוראreturn x hands a value back
      • שם פונקציה = פועל: add_bookFunction name = a verb: add_book
      • כל פונקציה עושה דבר אחדEach function does one thing

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

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

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