return מול print, משתנים מקומיים וגלובליים, ופונקציות טהורות.
return vs print, local and global variables, and pure functions.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.
חימום: 3 שאלותWarm-up: 3 questions
תרגיליםExercises
תרגילExercise 1
מ-print ל-returnFrom print to return
הפונקציה square מדפיסה במקום להחזיר, ולכן החישוב בשורה האחרונה נופל. תקנו אותה כך שתחזיר, והקוד ידפיס 26.
square prints instead of returning, so the last line crashes. Fix it to return, and the code prints 26.
איך הפלט אמור להיראות?What should the output look like?
26
main.py
רמזHint 1:מחליפים את print(...) ב-return ....Replace print(...) with return ....
הקוד משתמש במשתנה גלובלי ונופל עם UnboundLocalError. שכתבו את add_xp כך שתקבל את ה-XP הנוכחי ואת התוספת ותחזיר את החדש. הקוד הראשי צריך להדפיס 150.
The code uses a global and crashes with UnboundLocalError. Rewrite add_xp to take the current XP and the bonus and return the new value. The main code should print 150.
איך הפלט אמור להיראות?What should the output look like?
150
main.py
רמזHint 1:def add_xp(xp, bonus): return xp + bonusdef add_xp(xp, bonus): return xp + bonus
מדף, צעד 10: חיפוש שמחזיר תוצאותShelf, step 10: a search that returns results
פרויקט מלווהCompanion project
כתבו search(shelf, text) טהורה שמחזירה רשימה של מילוני ספרים שהכותרת או המחבר שלהם מכילים את text (בלי רגישות לאותיות גדולות). הדפיסו את הכותרות של התוצאות עבור "da".
Write a pure search(shelf, text) returning a list of book dicts whose title or author contains text (case-insensitive). Print the titles of the results for "da".
איך הפלט אמור להיראות?What should the output look like?
Matilda
shelf.py
רמזHint 1:t = text.lower()t = text.lower()
רמזHint 2:comprehension עם or.A comprehension with or.
כתבו digit_sum(n) רקורסיבית שמחזירה את סכום הספרות של מספר שלם חיובי, בלי להמיר למחרוזת. רמז: n % 10 היא הספרה האחרונה ו-n // 10 הוא השאר.
Write a recursive digit_sum(n) returning the digit sum of a positive integer, without converting to a string. Hint: n % 10 is the last digit and n // 10 is the rest.
איך הפלט אמור להיראות?What should the output look like?
10
main.py
רמזHint 1:תנאי עצירה: if n < 10: return n.Stop: if n < 10: return n.
רמזHint 2:return n % 10 + digit_sum(n // 10)return n % 10 + digit_sum(n // 10)