August 2019
Beginner
482 pages
12h 56m
English
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)Da
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 ...
Read now
Unlock full access