דיבאג עם VS CodeDebugging with VS Code
נקודות עצירה, צעד-אחר-צעד, צפייה במשתנים ושיטה למציאת באגים.
Breakpoints, stepping, watching variables and a method for finding bugs.
01שיטה למציאת באגיםA method for finding bugs
באג הוא פער בין מה שציפיתם למה שקרה. שיטה בארבעה צעדים: (1) לשחזר את הבאג בכוונה, (2) לצמצם את האזור, (3) להשוות בכל נקודה מה ציפיתם לראות מול מה שיש, (4) לתקן ולבדוק שוב. הקוד הבא מחזיר ממוצע שגוי. איפה?
A bug is a gap between what you expected and what happened. A four-step method: (1) reproduce it on purpose, (2) narrow the area, (3) at each point compare what you expected with what's there, (4) fix and check again. This code returns a wrong average. Where?
def average(nums):
total = 0
for n in nums:
total += n
print(f" debug: n={n}, total={total}")
return total / len(nums) + 1
print(average([10, 20, 30]))debug: n=10, total=10 debug: n=20, total=30 debug: n=30, total=60 21.0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
לחפש באג זה כמו לחפש נזילה בצנרת: לא מפרקים את כל הבית. סוגרים ברז אחרי ברז, עד שמוצאים את הקטע שבו המים בורחים.
Hunting a bug is like finding a leak in plumbing: you don't take the house apart. You close one valve after another until you find the section where water escapes.
ההדפסות מראות ש-total נכון (60). אז הבעיה אחרי הלולאה: ה-+ 1 המיותר. ככה צמצום עובד.
The prints show total is right (60). So the problem is after the loop: the stray + 1. That's narrowing down.
מנחשים ומשנים קוד באקראי במקום לבדוק. הנה בדיקה שמגלה שהתוצאה רחוקה מהציפייה.
Guessing and changing code at random instead of checking. Here's a check that shows the result is off.
def average(nums):
return sum(nums) / len(nums) + 1
result = average([10, 20, 30])
assert result == 20, f"expected 20, got {result}"Traceback (most recent call last):
File "/Users/you/python-course/method.py", line 5, in <module>
assert result == 20, f"expected 20, got {result}"
^^^^^^^^^^^^
AssertionError: expected 20, got 21.0AssertionError: expected 20, got 21.0: ההודעה אומרת בדיוק מה ציפינו ומה קיבלנו. מכאן מתחילים לצמצם.AssertionError: expected 20, got 21.0: the message says exactly what we expected and what we got. Narrowing starts here.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02הדיבאגר של VS CodeVS Code's debugger
הדיבאגר עושה בדיוק מה שהסימולטורים בקורס עושים, אבל על הקוד שלכם: עוצר בשורה ומראה את כל המשתנים. שמים נקודת עצירה (נקודה אדומה משמאל למספר השורה), לוחצים F5 ובוחרים Python File.
The debugger does exactly what this course's simulators do, but on your own code: it pauses on a line and shows every variable. Set a breakpoint (a red dot left of the line number), press F5 and choose Python File.
| מקשKey | פעולהAction | מתיWhen |
|---|---|---|
| F5 | להתחיל / להמשיך עד העצירה הבאהStart / continue to the next stop | תחילת דיבאגStart debugging |
| F10 | Step Over: שורה הבאהStep Over: next line | רוב הזמןMost of the time |
| F11 | Step Into: להיכנס לפונקציהStep Into: go inside a function | כשחושדים בפונקציהWhen you suspect a function |
| Shift+F11 | Step Out: לצאת מהפונקציהStep Out: leave the function | כשסיימתם לבדוק בפניםWhen done inside |
| Shift+F5 | לעצור את הדיבאגStop debugging |
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
דיבאגר הוא כמו להריץ סרט בהילוך איטי עם כפתור עצירה: אפשר לעצור בכל פריים ולבדוק מי עומד איפה.
A debugger is like playing a film in slow motion with a pause button: you can stop on any frame and check who's standing where.
שמים נקודת עצירה על שורה שאף פעם לא רצה, ומתפלאים שהדיבאגר לא עוצר. כאן ה-if אף פעם לא מתקיים.
Putting a breakpoint on a line that never runs, and wondering why it doesn't stop. Here the if never holds.
pages = 412
reached = False
if pages > 1000:
reached = True
assert reached, "the breakpoint line inside the if never ran: pages is only 412"Traceback (most recent call last):
File "/Users/you/python-course/debug.py", line 5, in <module>
assert reached, "the breakpoint line inside the if never ran: pages is only 412"
^^^^^^^
AssertionError: the breakpoint line inside the if never ran: pages is only 412AssertionError: אם הדיבאגר לא עוצר, כנראה שהשורה לא רצה. שמים נקודה מוקדם יותר ובודקים את התנאי.AssertionError: if the debugger doesn't stop, the line probably never runs. Put a breakpoint earlier and check the condition.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03הדפסות דיבאג חכמותSmart debug prints
לפעמים הדפסה מהירה עדיפה על דיבאגר. הטריק f"{x=}" מדפיס גם את שם המשתנה וגם את הערך. repr חושף רווחים נסתרים ומירכאות, וכך מגלים למה "Dune " לא שווה ל-"Dune".
Sometimes a quick print beats a debugger. The f"{x=}" trick prints both the variable's name and value. repr reveals hidden spaces and quotes, showing why "Dune " doesn't equal "Dune".
title = "Dune "
search = "Dune"
print(f"{title=}, {search=}")
print(title == search)
print(repr(title), len(title))
age = "30"
print(f"{age=} {type(age)=}")title='Dune ', search='Dune' False 'Dune ' 5 age='30' type(age)=<class 'str'>
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הדפסת דיבאג היא כמו להשאיר פתקים לעצמכם לאורך מבוך: "הייתי כאן, והמפתח היה בכיס".
A debug print is like leaving notes to yourself through a maze: "I was here, and the key was in my pocket".
משווים מחרוזות עם רווח נסתר. בלי repr לא רואים אותו בכלל.
Comparing strings with a hidden space. Without repr you can't see it.
stored = "Dune "
wanted = input("title: ")
assert stored == wanted, f"{stored!r} != {wanted!r}"title: Dune
Traceback (most recent call last):
File "/Users/you/python-course/prints.py", line 3, in <module>
assert stored == wanted, f"{stored!r} != {wanted!r}"
^^^^^^^^^^^^^^^^
AssertionError: 'Dune ' != 'Dune'AssertionError: 'Dune ' != 'Dune': ה-!r (repr) חושף את הרווח. מנקים עם strip() כשקוראים וכששומרים.AssertionError: 'Dune ' != 'Dune': the !r (repr) reveals the space. Clean with strip() when reading and saving.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
print באמצע לולאה מראה מה קורה בכל סיבוב.
A print inside a loop shows what happens each round.
nums = [4, 7, 1]
biggest = 0
for n in nums:
if n > biggest:
biggest = n
print("saw", n, "biggest so far", biggest)saw 4 biggest so far 4 saw 7 biggest so far 7 saw 1 biggest so far 7
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04assert: הנחות שבודקות את עצמןassert: assumptions that check themselves
assert בודק הנחה שאתם בטוחים בה. אם היא שגויה, התוכנית נעצרת מיד עם הודעה, במקום להמשיך עם נתונים שבורים ולהיכשל במקום רחוק ומבלבל. כך עובדות גם הבדיקות האוטומטיות של התרגילים באתר.
assert checks an assumption you're sure of. If it's wrong, the program stops at once with a message, instead of carrying on with broken data and failing somewhere far and confusing. The site's exercise checks work this way too.
def percent(read, total):
assert total > 0, "total pages must be positive"
assert 0 <= read <= total, f"read={read} is outside 0..{total}"
return round(read / total * 100)
print(percent(103, 412))
assert percent(0, 10) == 0
assert percent(10, 10) == 100
print("כל הבדיקות עברו")def percent(read, total):
assert total > 0, "total pages must be positive"
assert 0 <= read <= total, f"read={read} is outside 0..{total}"
return round(read / total * 100)
print(percent(103, 412))
assert percent(0, 10) == 0
assert percent(10, 10) == 100
print("all checks passed")25 כל הבדיקות עברו
25 all checks passed
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
assert הוא כמו נורת "חגורה לא חגורה" ברכב: לא מחכה לתאונה כדי להודיע שמשהו לא בסדר.
assert is like the car's seatbelt warning light: it doesn't wait for a crash to tell you something's wrong.
הנחה שהופרה: מספר העמודים שקראו גדול מהספר.
A broken assumption: more pages read than the book has.
def percent(read, total):
assert 0 <= read <= total, f"read={read} is outside 0..{total}"
return round(read / total * 100)
print(percent(500, 412))Traceback (most recent call last):
File "/Users/you/python-course/assert_demo.py", line 5, in <module>
print(percent(500, 412))
~~~~~~~^^^^^^^^^^
File "/Users/you/python-course/assert_demo.py", line 2, in percent
assert 0 <= read <= total, f"read={read} is outside 0..{total}"
^^^^^^^^^^^^^^^^^^
AssertionError: read=500 is outside 0..412AssertionError: read=500 is outside 0..412: הבאג נתפס במקום שבו הוא נכנס, עם הסבר.AssertionError: read=500 is outside 0..412: the bug is caught where it entered, with an explanation.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
assert שותק כשהכל בסדר.
assert stays quiet when all is well.
def average(nums):
return sum(nums) / len(nums)
assert average([2, 4]) == 3
assert average([5]) == 5
print("all checks passed")all checks passed
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05logging: הדפסות שאפשר לכבותlogging: prints you can switch off
logging הוא כמו print עם מתג עוצמה. כל הודעה מקבלת רמה, וההגדרה קובעת מאיזו רמה מציגים. בזמן פיתוח מציגים DEBUG, ובתוכנית גמורה רק WARNING ומעלה, בלי לגעת בקוד.
logging is like print with a volume knob. Each message has a level, and the setting decides from which level to show. During development show DEBUG; in a finished program only WARNING and up, without touching the code.
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stdout)
log = logging.getLogger("shelf")
log.debug("loading file...")
log.info("loaded 3 books")
log.warning("book without author: Dune")
log.error("could not save")INFO: loaded 3 books WARNING: book without author: Dune ERROR: could not save
logging הוא כמו רמקול עם בורר ערוצים: בזמן חזרות שומעים הכול, ובהופעה רק הודעות חשובות.
logging is like a speaker with a channel selector: in rehearsal you hear everything, at the show only the important messages.
טעות כתיב ברמה: אין logging.WARN_ING.
A typo in a level name: there's no logging.WARN_ING.
import logging
logging.basicConfig(level=logging.WARN_ING)Traceback (most recent call last):
File "/Users/you/python-course/logging_demo.py", line 2, in <module>
logging.basicConfig(level=logging.WARN_ING)
^^^^^^^^^^^^^^^^
AttributeError: module 'logging' has no attribute 'WARN_ING'. Did you mean: 'WARNING'?AttributeError: module 'logging' has no attribute 'WARN_ING': השמות הם DEBUG, INFO, WARNING, ERROR, CRITICAL.AttributeError: module 'logging' has no attribute 'WARN_ING': the names are DEBUG, INFO, WARNING, ERROR, CRITICAL.06באגים קלאסייםClassic bugs
כמה באגים חוזרים אצל כולם: טעות באחד בגבולות (off-by-one), return בתוך לולאה במקום אחריה, ושורה בהזחה הלא נכונה. כשנתקעים, שיטת הברווז עובדת להפליא: מסבירים כל שורה בקול, ובאמצע ההסבר הטעות קופצת.
A few bugs hit everyone: off-by-one at the edges, a return inside a loop instead of after it, and a line at the wrong indentation. When stuck, rubber duck debugging works wonders: explain each line out loud, and halfway through the mistake jumps out.
def total_buggy(nums):
total = 0
for n in nums:
total += n
return total
def total_fixed(nums):
total = 0
for n in nums:
total += n
return total
print(total_buggy([1, 2, 3]), total_fixed([1, 2, 3]))1 6
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
שיטת הברווז עובדת כי כשמסבירים, המוח עובר מ"מה שהתכוונתי" ל"מה שכתוב בפועל".
The duck works because explaining moves your brain from "what I meant" to "what's actually written".
off-by-one: הלולאה מפספסת את האחרון. בדיקה חושפת.
Off-by-one: the loop misses the last item. A check exposes it.
days = 7
count = 0
for d in range(1, days):
count += 1
assert count == 7, f"counted {count} days, expected 7"Traceback (most recent call last):
File "/Users/you/python-course/classic.py", line 5, in <module>
assert count == 7, f"counted {count} days, expected 7"
^^^^^^^^^^
AssertionError: counted 6 days, expected 7AssertionError: counted 6 days, expected 7: range(1, days) עוצר לפני 7. כותבים range(1, days + 1).AssertionError: counted 6 days, expected 7: range(1, days) stops before 7. Write range(1, days + 1).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.