קבצים ושגיאות
הוצגבשיעור הזה
| English | משמעות |
|---|---|
| exception/ekˈsepʃn/ | חריגה |
Why does the game crash for new players?
- A game reads the player's text size from
settings.txt. It works on the developer's computer. On a new player's first run there is no file yet, and the game stops withFileNotFoundError. - Programs meet a messy world: missing files, typing mistakes, bad data. This lesson shows how to read and write files, and how to plan for the errors you can expect.
Reading a file
with open("scores.txt") as f:opens the file and closes it for you when the block ends, even if an error happens inside.- Looping
for line in f:gives one line at a time, with its"\n"on the end. Callline.strip()before you split or convert it.
total = 0
# the file holds lines like Ana,72
with open("scores.txt") as f:
for line in f:
name, mark = line.strip().split(",")
total += int(mark)
print(total) # 217
קובץ מכיל שלוש שורות: Ana,72, Ben,55, Cai,90. הלולאה מוסיפה int(line.strip().split(",")[1]) לכל שורה. מה הסכום הכולל?
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
$72 + 55 + 90 = 217$. strip() מסיר את "\n", split(",") מפריד את השם מהציון, ו-[1] לוקח את הציון.
Writing a file
open(path, "w")empties the file first, then writes.open(path, "a")appends to the end and keeps what was there.f.write()takes a string and adds no line break, so writef.write(name + "\n")orf.write(f"{name},{mark}\n").
התאם כל מצב למה שהוא עושה.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
"r" היא ברירת המחדל. בחירת "w" לקובי יומן שהייתה אמור להרחיב תרוקן אותו בכל ריצה.
Errors have names
- When something goes wrong, Python raises an exception 异常, and each kind has a name:
FileNotFoundError(no such file),ValueError(int("x")),KeyError(missing dictionary key),TypeError("a" + 1),ZeroDivisionError(1 / 0). - The name is the most useful line of an error message. Read it first, then the line number above it.
התאם כל שורה לסטייה שהיא גורמת.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
A ValueError הוא סוג נכון עם ערך שגוי; A TypeError הוא סוג שגוי לפעולה.
try and except
- Put the risky lines in a
try:block and the plan for one named error in anexcept ValueError:block. If that error happens, Python jumps straight to theexceptblock. - Lines in the
tryblock after the failing line are skipped. Code after the wholetry … exceptruns as normal.
try:
print("A")
n = int("seven") # ValueError here
print("B") # skipped
except ValueError:
print("C")
print("D") # prints A, C, D
מה מדפיא התוכנית A/B/C/D? try: מדפיא A, רץ int("seven"), מדפיא B; except ValueError: מדפיא C; לאחר מכן D מודפס אחרי החסימה.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
A מודפס, ואז int("seven") גורם לסטייה. שאר החסימה try, כולל B, מוחלצת; C רץ; D רץ כי הוא אחרי החסימה כולה.
Ask again until the input is good
- Put
try … exceptinside awhile True:loop. A good value reachesreturn, which leaves the loop and the function together. A bad value is caught, and the loop asks again. - The user who types
xand then4sees one message and the program carries on with4.
def read_count():
while True:
try:
return int(input("How many? "))
except ValueError:
print("Whole numbers only.")
משתמש הזין x, אחר כך 2.5, ואז 4 לתוך read_count(). כמה פעמים מודפסת ההודעה "מספרים שלמים בלבד"?
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
int("x") ו-int("2.5") שניהם גורמים ל-ValueError, אז ההודעה מופיעה פעמיים. int("4") עובד ו-return מסיים את הלולאה.
One outcome, several roads
- Robust code tries the normal path, names each failure it expects and gives each one a sensible fallback. The caller always gets a usable result.
- Catch only what you have a plan for. A typing mistake in your own code should still crash loudly so you can find it.

- Read the text size from
settings.txt; use 12 if the file is missing or does not hold a whole number. try:open the file andsize = int(f.read().strip()).except FileNotFoundError: size = 12andexcept ValueError: size = 12.- A file holding
16gives 16; no file gives 12; a file holdingbiggives 12. New players no longer see a crash.
סדרו את שורות קורא ההגדרות בסדר הנכון.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
הפעלה והמרה הסיכוןיות נכנסות לtry. פריט except אחד יכול לציין שני שגיאות בטופל כאשר לשניהן מיועדת אותה תוצאה ברירת מחדל.
Marks that slip away
- A bare
except:. It catches every error, including your own bugs, and hides them. Name the error you expect. - A huge
tryblock. Keep only the risky lines inside, so you know which line theexceptis answering. "w"when you meant"a"."w"wipes the old contents first.- Forgetting
strip()and"\n". Lines read in keep their line break; lines written out need one.
except: ללא תנאי הוא הבחירה הבטוחה ביותר, כי היא מונעת מהתוכנית להיקרס לעולם.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
היא גם בולעת את השגיאות שלך, כמו שם משתנה שכתוב לא נכון, כך שהן נכשלות בשקט. ציין את השגיאה הצפויה שאתה יכול להשיב עליה.
You've got it
with open(...)closes the file for you. Strip lines you read; add"\n"to lines you write.
| Mode | Does | File missing |
|---|---|---|
"r" |
reads | error |
"w" |
empties, then writes | creates it |
"a" |
adds to the end | creates it |
- An exception has a name.
try … except Name:catches that one error; the rest of thetryblock is skipped. - Catch only the errors you can answer, give each a fallback, and let unexpected errors crash so you can fix them.
מה השתבש? רק צוות האתר רואה זאת.