Chapter 10
10.1 Buggy cat naps
A way to approach this:
- Run the code and observe the output: hmmm, total is 8.5 instead of expected 10.5.
- Use
printstatements to see what values are being added or add a breakpoint in thewhileloop to inspectcounterandtotalvalues:- Print the
countervalue - Print the value being added each iteration
- Print the
- Notice that the first nap (2 hours) is never added.
- Identify the bug:
whileloop starts atcounter=1, skipping index 0.
Fix in the while loop OR use a for loop to eliminate indexing issues entirely (even cleaner solution).
def nap_time(hours_list):
total = 0
# BREAKPOINT at the original while loop: Step through to see which values get added
# Why: This reveals that index 0 is skipped (counter starts at 1)
for nap in hours_list:
total += nap
return total
cat_naps = [2, 3, 1.5, 4]
print("Total nap time:", nap_time(cat_naps))
# Expected...