שגיאות ו-try/exceptErrors & try/except
איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.
How to read a traceback, exception types, try/except/else/finally and raise.
חילוק בטוחSafe division
תזכורת: מה ביקשוReminder: the task
כתבו 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).
הפתרון המלא והפלט שלוFull solution and its output
def safe_div(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_div(10, 4))
print(safe_div(1, 0))2.5 None
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
קלט עמידRobust input
תזכורת: מה ביקשוReminder: the task
בקשו גיל עד שמגיע מספר שלם בין 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>.
הפתרון המלא והפלט שלוFull solution and its output
while True:
try:
age = int(input("age: "))
except ValueError:
print("not a number")
continue
if 0 <= age <= 120:
break
print("out of range")
print(f"age: {age}")age: old not a number age: 200 out of range age: 42 age: 42
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מילון בלי KeyErrorDict without KeyError
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def get_price(prices, item):
try:
return prices[item]
except KeyError:
raise ValueError(f"unknown item: {item}")
prices = {"milk": 6.9}
print(get_price(prices, "milk"))
try:
get_price(prices, "cake")
except ValueError as e:
print(e)6.9 unknown item: cake
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
סיכום עם דילוגSum while skipping
תזכורת: מה ביקשוReminder: the task
נתונה רשימת מחרוזות מקובץ מבולגן. סכמו רק את מה שאפשר להמיר ל-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.
הפתרון המלא והפלט שלוFull solution and its output
raw = ["412", "96", "n/a", "1036", "", "280", "lots"]
total = 0
skipped = 0
for r in raw:
try:
total += int(r)
except ValueError:
skipped += 1
print(f"sum: {total}, skipped: {skipped}")sum: 1824, skipped: 3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 11: קלט שלא קורסShelf, step 11: input that never crashes
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def ask_int(prompt, low, high):
while True:
try:
n = int(input(prompt))
except ValueError:
print("please type a number")
continue
if low <= n <= high:
return n
print(f"between {low} and {high}")
title = input("title: ")
pages = ask_int("pages: ", 1, 5000)
rating = ask_int("rating: ", 1, 5)
print(f"{title}: {pages} pages, {rating}/5")title: Dune pages: many please type a number pages: 412 rating: 9 between 1 and 5 rating: 4 Dune: 412 pages, 4/5
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מחשבון עמידA robust calculator
תזכורת: מה ביקשוReminder: the task
קלטו ביטוי בפורמט 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.
הפתרון המלא והפלט שלוFull solution and its output
def calc(line):
a, op, b = line.split()
try:
x, y = float(a), float(b)
except ValueError:
return "bad number"
try:
if op == "+":
return x + y
if op == "-":
return x - y
if op == "*":
return x * y
if op == "/":
return x / y
except ZeroDivisionError:
return "division by zero"
return "unknown operator"
for line in ["12 / 4", "5 / 0", "x + 1", "2 ^ 3"]:
print(calc(line))3.0 division by zero bad number unknown operator
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שגיאה מותאמתA custom error
תזכורת: מה ביקשוReminder: the task
הגדירו חריגה משלכם: 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.
הפתרון המלא והפלט שלוFull solution and its output
class BookError(Exception):
pass
def add_book(shelf, title):
if title in shelf:
raise BookError(f"duplicate: {title}")
shelf.append(title)
shelf = []
for t in ["Dune", "Emma", "Dune"]:
try:
add_book(shelf, t)
except BookError as e:
print(e)
print(shelf)duplicate: Dune ['Dune', 'Emma']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.