Python Break and Continue Statements
Break Statement (Used to exit a 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.
Continue Statement (Used to exit an iteration)
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.
Estimated Time
4 mins
Estimated Time
4 mins
Skill Level
Intermediate
Functions
na
Course Provider
Provided by HolyPython.com
Used Where?
break
is usually used for:
- Ending the loop prematurely.
continue
is usually used for:
- Skipping the iteration and continuing with the loop.
Syntax do(s)
1) type break inside a loop
2) type continue inside a loop
Syntax don't(s)
1) Don't forget indentation
Example 1
>>> 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.
Example 2
>>> 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.
Tips
1- N/A
Advanced Concepts (Optional)
1- N/A