Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
טיפול בחריגות
כשמתכנתים, שגיאות מתרחשות. זה פשוט עובדת חיים.
אולי המשתמש נתן קלט לא תקין. אולי משאב רשת לא היה זמין. אולי התוכנית נגמרה מהזיכרון. או שהמתכנת אולי אפילו עשה טעות!
הפתרון של פייתון לשגיאות הוא חריגים. ייתכן שכבר נתקלתם בחריג בעבר.
print(a)
#שגיאה
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
אופס! שכחנו להקצות ערך למשתנה 'a'.
אבל לפעמים אתם לא רוצים שחריגים יפסיקו את התוכנית לחלוטין. ייתכן שתרצו לעשות משהו מיוחד כשמתרחש חריג. זה נעשה בבלוק try/except.
הנה דוגמה פשוטה: נניח שאתם עושים לולאה על רשימה. אתם צריכים לעבור על 20 מספרים, אך הרשימה נוצרת מקלט משתמש, וייתכן שאין בה 20 מספרים. לאחר שתגיעו לסוף הרשימה, אתם פשוט רוצים שהמספרים הנותרים יתפרשו כ-0. הנה איך שתוכלו לעשות זאת:
def do_stuff_with_number(n):
print(n)
def catch_this():
the_list = (1, 2, 3, 4, 5)
for i in range(20):
try:
do_stuff_with_number(the_list[i])
except IndexError: # Raised when accessing a non-existing index of a list
do_stuff_with_number(0)
catch_this()
הנה, זה לא היה קשה מדי! אתם יכולים לעשות זאת עם כל חריג. לפרטים נוספים על טיפול בחריגים, אל תסתכלו רחוק יותר מהתיעוד של פייתון
תרגיל
טפלו בכל החריגים! תחשבו בחזרה על השיעורים הקודמים כדי להחזיר את שם המשפחה של השחקן.
# Setup
actor = {"name": "John Cleese", "rank": "awesome"}
# Function to modify!!!
def get_last_name():
return actor["last_name"]
# Test code
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
actor = {"name": "John Cleese", "rank": "awesome"}
def get_last_name():
return actor["name"].split()[1]
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
test_output_contains("Cleese")
test_output_contains("All exceptions caught! Good job!")
test_output_contains("The actor's last name is Cleese")
success_msg("Great work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!