effectivepython
effectivepython copied to clipboard
Item 35, pages 136 & 137: `while` loop does not break at 0, needs another `break` statement
(2nd ed)
Expected result
Program should stop at 0:
3 ticks left
2 ticks left
1 ticks left
3 ticks left
2 ticks left
1 ticks left
0 ticks left
Actual result
Program runs on, down to -1:
3 ticks left
2 ticks left
1 ticks left
3 ticks left
2 ticks left
1 ticks left
0 ticks left
3 ticks left
3 ticks left
2 ticks left
1 ticks left
0 ticks left
-1 ticks left
Fix
Add an additional conditional break statement at the end of the run() function on both pages 136 and 137:
# page 136
def run():
it = timer(4)
while True:
try:
if check_for_reset():
current = it.throw(Reset())
else:
current = next(it)
except StopIteration:
break
else:
announce(current)
if current == 0: # add this line
break # add this line
# page 137
def run():
timer = Timer(4)
for current in timer:
if check_for_reset():
timer.reset()
announce(current)
if current == 0: # add this line
break # add this line