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

PythonPython
11
חלקPart 2: פונקציות וקוד אמיתיFunctions & real code כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

שגיאות ו-try/exceptErrors & try/except

איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.

How to read a traceback, exception types, try/except/else/finally and raise.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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

1. ב-Traceback, איזו שורה אומרת מה סוג השגיאה?In a traceback, which line names the error type?

2. מה ידפיס הקוד?What does this print?
python
try:
    x = 1 / 0
    print("A")
except ZeroDivisionError:
    print("B")
finally:
    print("C")

3. מתי משתמשים ב-raise?When do you use raise?

תרגיליםExercises

תרגילExercise 1

חילוק בטוחSafe division

כתבו safe_div(a, b) שמחזירה a / b, ואם b הוא 0 מחזירה None (בעזרת try/except, לא if). הדפיסו safe_div(10, 4) ו-safe_div(1, 0).

Write safe_div(a, b) returning a / b, or None if b is 0 (using try/except, not if). Print safe_div(10, 4) and safe_div(1, 0).

איך הפלט אמור להיראות?What should the output look like?
2.5
None
main.py
רמזHint 1: except ZeroDivisionError: return Noneexcept ZeroDivisionError: return None
לפתרוןSolution
תרגילExercise 2

קלט עמידRobust input

בקשו גיל עד שמגיע מספר שלם בין 0 ל-120. על טקסט הדפיסו not a number, על מספר מחוץ לטווח out of range. בסוף הדפיסו age: <גיל>.

Ask for an age until a whole number from 0 to 120 arrives. For text print not a number, for a number out of range out of range. Finally print age: <age>.

איך הפלט אמור להיראות?What should the output look like?
age: old
not a number
age: 200
out of range
age: 42
age: 42
main.py
רמזHint 1: while True + try/except ValueError.while True + try/except ValueError.
רמזHint 2: continue אחרי הודעה, break כשתקין.continue after a message, break when valid.
לפתרוןSolution
תרגילExercise 3

מילון בלי KeyErrorDict without KeyError

כתבו get_price(prices, item) שמחזירה את המחיר, ואם אין מוצר כזה זורקת ValueError עם ההודעה unknown item: <item>. בקוד הראשי תפסו את השגיאה והדפיסו את ההודעה שלה.

Write get_price(prices, item) returning the price, or raising ValueError with the message unknown item: <item> if missing. In the main code catch it and print its message.

איך הפלט אמור להיראות?What should the output look like?
6.9
unknown item: cake
main.py
רמזHint 1: תופסים KeyError בתוך הפונקציה וזורקים ValueError.Catch KeyError inside and raise ValueError.
רמזHint 2: except ValueError as e: print(e)except ValueError as e: print(e)
לפתרוןSolution
תרגילExercise 4

סיכום עם דילוגSum while skipping

נתונה רשימת מחרוזות מקובץ מבולגן. סכמו רק את מה שאפשר להמיר ל-int, וספרו כמה דילגתם. הדפיסו sum: X, skipped: Y.

Given a list of strings from a messy file, sum only those that convert to int, and count how many you skipped. Print sum: X, skipped: Y.

איך הפלט אמור להיראות?What should the output look like?
sum: 1824, skipped: 3
main.py
רמזHint 1: try/except ValueError בתוך הלולאה.try/except ValueError inside the loop.
רמזHint 2: שני צוברים.Two accumulators.
לפתרוןSolution
תרגילExercise 5

מדף, צעד 11: קלט שלא קורסShelf, step 11: input that never crashes

פרויקט מלווהCompanion project

כתבו ask_int(prompt, low, high) שמבקשת מספר עד שמגיע מספר שלם בטווח, ומחזירה אותו. השתמשו בה כדי לקלוט מספר עמודים (1-5000) ודירוג (1-5) לספר, והדפיסו Dune: 412 pages, 4/5.

Write ask_int(prompt, low, high) that asks until a whole number in range arrives, then returns it. Use it to read a book's pages (1-5000) and rating (1-5), and print Dune: 412 pages, 4/5.

איך הפלט אמור להיראות?What should the output look like?
title: Dune
pages: many
please type a number
pages: 412
rating: 9
between 1 and 5
rating: 4
Dune: 412 pages, 4/5
shelf.py
רמזHint 1: לולאה + try בתוך הפונקציה.A loop + try inside the function.
רמזHint 2: return במקום break.return instead of break.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

מחשבון עמידA robust calculator

קלטו ביטוי בפורמט a op b (למשל 12 / 4). הדפיסו את התוצאה. על מספר לא תקין הדפיסו bad number, על חילוק באפס division by zero, ועל אופרטור לא מוכר unknown operator.

Read an expression like a op b (e.g. 12 / 4). Print the result. For a bad number print bad number, for division by zero division by zero, and for an unknown operator unknown operator.

איך הפלט אמור להיראות?What should the output look like?
3.0
division by zero
bad number
unknown operator
main.py
רמזHint 1: a, op, b = input().split()a, op, b = input().split()
רמזHint 2: זריקת ValueError משלכם לאופרטור לא מוכר.Raise your own error for an unknown operator.
לפתרוןSolution
אתגרChallenge 2

שגיאה מותאמתA custom error

הגדירו חריגה משלכם: class BookError(Exception): pass. כתבו add_book(shelf, title) שזורקת BookError("duplicate: <title>") אם הספר כבר קיים. הוסיפו Dune, Emma, Dune ותפסו את השגיאה.

Define your own exception: class BookError(Exception): pass. Write add_book(shelf, title) that raises BookError("duplicate: <title>") if the book already exists. Add Dune, Emma, Dune and catch the error.

איך הפלט אמור להיראות?What should the output look like?
duplicate: Dune
['Dune', 'Emma']
main.py
רמזHint 1: מחלקות נלמד במפגש 15; כאן מספיקה השורה הזו כמו שהיא.Classes come in session 15; this one line is enough for now.
רמזHint 2: except BookError as e:except BookError as e:
לפתרוןSolution

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