Logo

Developer learning path

Python

Break and Continue Statements in Python

Break and Continue Statements

12

#description

In Python, break and continue are two statements that can be used to control the flow of execution in a loop.

The break statement is used to immediately terminate a loop. When executed inside a loop (for loop or while loop), the loop is exited immediately and program execution proceeds to the next statement after the loop.

For example:

                    
for i in range(1, 6):
    if i == 3:
        break
    print(i)
                  

Here, when the loop variable i becomes 3, the break statement is executed and the loop is exited immediately. Therefore, only 1 and 2 are printed.

The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When executed inside a loop (for loop or while loop), program execution jumps to the next loop iteration without executing any remaining statements in the current iteration.

For example:

                    
for i in range(1, 6):
    if i == 3:
        continue
    print(i)
                  

Here, when the loop variable i becomes 3, the continue statement is executed and the loop moves to the next iteration without printing 3. Therefore, 1, 2, 4, and 5 are printed.

These statements can be especially useful when dealing with complex loops where you want to stop execution under certain conditions or skip certain iterations of the loop.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.