Breaking out of loops

30 Jan, 2021

Sherry W writes (excerpted):

Excellent book so far for my grandson.

On page 78 should it read?:

while True:
    lots of code here
    lots of code here
    lots of code here
    if some value == False
        break

Book is written very well for that age group. It’s great to have a book that is able to explain concepts with simple examples.

The example on page 78 is not supposed to be executable code (obviously the text "lots of code here" repeated 3 times isn't), so it doesn't actually matter if the condition is "some_value == False" or "some_value == True". If I was going to write a runnable version of the example, it might look something like this:

some_value = True
while True:
    print("aaaa")
    print("bbbb")
    print("cccc")
    if some_value == True:
        break 

Which, if it was run, would print the following just once:

aaaa
bbbb
cccc

But you could use True or False in the above example (on the first line and the second-to-last line), and it would work just as well.

However a shortcut, not mentioned in the book (because I think simplicity and clarity is better for beginners), is that when you're checking for True, you can omit the "== True" altogether:

some_value = True
while True:
    print("aaaa")
    print("bbbb")
    print("cccc")
    if some_value:
        break