Procedures & functions · פרוצדורות ופונקציות
A function is a named block
- A function is a named block of code you can run again and again.
- Define it once with
def, then call it by name. - This avoids repeating yourself and keeps programs tidy.
פונקציה היא חבילה קוד בעלת שם
- פונקציה היא חבילת קוד בעלת שם שתוכל להפעיל שוב ושוב.
- הגדר אותה פעם אחת עם
def, ולאחר מכן היא אותה לפי שמה. - הדבר מונע חזרה על עצמך ומשמר את התוכניות מסודרות.
def greet():
print("Hello!")
greet()
greet()
Parameters pass data in
- A parameter is a value the function receives.
- Put it in the brackets, and pass an argument when you call.
- Keep the number of parameters small so the function stays easy to read.
פרמטרים מעבירים נתונים לתוך
- פרמטר הוא ערך שהפונקציה מקבלת.
- שימו אותו בסוגריים, והעבירו ארגומנט כאשר אתם קוראים לה.
- שמרו על מספר קטן של פרמטרים כך שהפונקציה תישאר קלה לקריאה.
def greet(name):
print("Hello, " + name)
greet("Ada")
greet("Sam")
Functions return a value
- A function hands a value back with
return. - A block that only does something and returns nothing is a procedure.
פונקציות מחזירות ערך
- פונקציה מחזירה ערך באמצעות
return. - חבילה שעושה רק פעולה ואינה מחזירה דבר היא פרוצדורה.
def square(n):
return n * n
answer = square(6)
print(answer) # 36
Call and return · קריאה והשבה
Calling runs the function's body; return hands a value back. · קריאה מפעילה גוף הפונקציה; return מחזירה ערך חזרה.
In the exam: PROCEDURE and FUNCTION
- Pseudocode separates a
PROCEDURE(no result) from aFUNCTION(returns a value).
במבחן: PPROCEDURE ו-FUNCTION
- הפסאו-קוד מפריד בין
PROCEDURE(ללא תוצאה) לביןFUNCTION(מחזיר ערך).
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
Common mistakes
- A function returns a value with
return; a procedure just does a job. - Call it with
(). - Parameters receive the arguments in order.
טעויות נפוצות
- פונקציה מחזירה ערך עם
return; פרוצדורה פשוט מבצעת משימה. - קרא אליה עם
(). - הפרמטרים מקבלים את הארגומנטים בסדר.
Now you try
- Write each function — it is then called for you in the check.
- Press Check answer to test your code.
כעת תנסו בעצמכם
- כתוב כל פונקציה — היא תיקרא עבורך במבחן הבדיקה.
- לחץ על בדוק תשובה כדי לבדוק את הקוד שלך.
Write a function double(n) that returns n times 2. · כתוב פונקציה double(n) שתחזיר n כפול 2.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a function is_even(n) that returns True when n is even, otherwise False. · כתוב פונקציה is_even(n) שתחזיר True כאשר n הוא זוגי, אחרת תחזיר False.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a procedure print_stars(n) that prints a line of n star (*) characters, then call it with 4 so it prints ****. · כתוב פרוצדורה print_stars(n) שמדפיקה שורה של n כוכבים (* תווים), ולאחר מכן קרא אליה עם 4 כך שתדפיק ****.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.