bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.2k stars 710 forks source link

Item 35, pages 136 & 137: `while` loop does not break at 0, needs another `break` statement #112

Closed kirisakow closed 1 month ago

kirisakow commented 1 year ago

(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
bslatkin commented 1 month ago

Thank you for the report. @kirisakow I can't reproduce the behavior where it counts down to -1. Do you have a full example of the code that exhibits this behavior? I'm sorry for the extremely long delay in getting back to you!

kirisakow commented 1 month ago

Hello Brett, although I've kept the Jupyter notebook with the code examples from your book, however, as of today, I can't reproduce the abnormal behavior. I can't tell why... Perhaps, in the meantime something has been fixed in the underlying Jupyter modules.

bslatkin commented 1 month ago

👍 thank you so much for checking! Okay I'm going to close this one, but please feel free to reopen if you ever see it again. I really appreciate all of your feedback!