Additional loop functionality – break and continue

At any point, the loop can be broken from inside. Using the break keyword, the loop will be terminated immediately. The following code loops over the string and halts the loop once the letter is equal to t. As t is the third letter, the loop is only able to print the first two letters:

>>> for letter in "Data":
>>> if letter == 't':
>>> break
>>> print(letter)
D
a

The break keyword is especially useful for infinite loops, which can be triggered to stop if a certain condition is met.

Alternatively, if you just need to skip one round without stopping the entire loop, you can use the continue keyword. We execute the same example—except this time, if the letter is equal to 't', the loop will skip one round of execution and jump to the next one for the letter 'a':

>>> for letter in "Data":
>>> if letter == 't':
>>> continue
>>> print(letter)
D
a
a

break and continue will work with both types of loops. Both are relatively rare, but could prove invaluable in specific cases; for example, when you need to stop the traverse on a certain condition. It could be because you need it as part of your algorithm, or if you want to halt/pass on an invalid case, which can cause errors. 

Our next compound statement is designed specifically to handle the errors so that your code will survive and adjust accordingly. Let's see how this is done.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset