This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Breaking the flow

Another use case for break

face Josiah Wang

Here is another use case for break. Try to understand what the code does before moving on!

1
2
3
4
5
6
7
while True:
    line = input("> ")
    if line == "quit":
        break
    print(line)

print("Terminating program!")

While we discourage using while True in general (it is sometimes hard to read and there is a chance of producing an infinite loop), this is an example where its use is perfectly acceptable.

Compare the code above to a more structured style of programming below, which requires you to repeat the statement line = input("> ") twice (Lines 1 and 4).

1
2
3
4
5
6
line = input("> ")
while line != "quit":
    print(line)
    line = input("> ")

print("Terminating program!")

Both methods are valid and produce the same behaviour. But you might prefer one over another depending on your use case. Choose the most suitable and readable option!