Python break statement


Introduction to the use of break and continue. Python break statements, like in C, break the least closed for or while loop.

The break statement is used to terminate the loop statement, i.e. the loop condition is not False or the sequence has not been fully recursively completed. The break statement is used in the while and for loops.

If a nested loop is used, the break statement stops the deepest loop and starts the next line of code.

Related course: Complete Python Programming Course & Exercises

break syntax

Python continue out of this loop after break is called

for l in letters:
    break

continue

The continue statement is used to tell Python to skip the remaining statements of the current loop, and then proceed to the next cycle.

The continue statement is used in the while and for loops. The Python language continue statement has the following syntax.

Break examples

Example of break.

for letter in 'Python': # first example
   if letter == 'h':
      break
   print('current letter :', letter)

python for loop break

An example of break in a while loop:

var = 10 # Second instance
while var > 0. print 'Current variable value :', var              
   print('Current variable value :', var)
   var = var -1
   if var == 5: # Exit the loop when the variable var is equal to 5
      break

print "Good bye!"

You'll find the results after running.

Example of a "continue" statement.

The program below demonstrates the use of continue:

#! /usr/bin/python
# -*- coding: UTF-8 -*-
for letter in 'python':
    if letter=='h':
        continue
    print("Current letter: %s" %letter)

Another example:

var=12
while var > 0:    
    var=var-1
    if var==5:
        continue

    print("Current variable: %s" %var)

python while continue

It's really important to be strictly indented in python (four spaces, not tabs).

The loops for and while both can use break and continue.

In other languages

In C, C++ or Java you can do something like this:

for(initial condition; termination condition; number of cycles)
{
What to loop;
}
while(a condition)
{
core code
}

But python is different:

Without brackets, but using spaces as indetion. The beginner can be very confused and will not know why he or she is seeing an error.

Summary

Today you learned the difference between break and continue statement.

  • The break statement in Python is used to exit the loop.
  • You can not use break statement outside the loop, it will throw the error SyntaxError: ‘break’ outside loop
  • You can use break statement with a for loop or a while loop
  • If the break statement is inside a nested loop, it exits the inner loop
  • break is a reserved keyword in Python