
Bug hunt
The Haunted Backpack
Here's one of Python's most famous traps. A default value is created
once, when the def line runs, not each time the function is
called. For numbers and strings that's harmless. But a default
list is shared by every call, so changes pile up!
The fix is to use None as the default, and make a fresh list
inside the function:
def add_note(note, notes=None):
if notes is None:
notes = [] # a new list on every call
notes.append(note)
return notes
The bug
Ada and Bo each pack a brand-new bag, but somehow they end up sharing one:
Ada: ['rope', 'map']
Bo: ['rope', 'map']
Assignment
Fix pack so every call without a bag starts with its own
empty list. Passing an existing bag should still work.
Fix pack so every call without a bag starts with its own
empty list. Passing an existing bag should still work.
main.py Python sleeping
Press Run to try your code, then Check to test it.