Used Where?
Break and Continue statements give you more advanced control over your loops (for or while).
break is usually used for: - Ending the loop prematurely.
continue is usually used for: - Skipping the iteration and continuing with the loop.
Break statement is used to exit a loop before it loops all the way through.
Simply type break where you want the loop to end.
In some situations you might need a nested loop structure. We have previously seen that lists can be consisted of many type of different data including other lists.
Let’s see an example of nested list and nested for loop.
Continue statement makes the program skip the current iteration and return to the top of the loop. All the statements and functions after the continue statement will be neglected for that particular iteration.
4 mins
4 mins
Intermediate
na
Provided by HolyPython.com
break is usually used for: continue is usually used for:
1) type break inside a loop
2) type continue inside a loop
1) Don't forget indentation
>>> for i in range(100):
>>> print(i)
>>> if i == 5:
>>> break
0
1
2
3
4
5
As you can see instead of looping all the way until 100, once i equals 5, break is executed and loop ends.
>>> for i in [“milk”, “bread”, [“cake”, “cherry”]:
>>> for j in i:
>>> if i == “cake”
>>> continue
>>> print(i)
milk
bread
cherry
As you can see continue causes to skip the current iteration and loop continues without executing the command after that particular iteration.
1- N/A
1- N/A