Python Loop Control Statements

Now that we have seen a few Python loops in action, its's time to take a look at two simple statements that have a purpose only when nested inside loops- the break and continue statements.

Python supports the following control statements.

  • break
  • continue
  • pass (Does nothing at all: its an empty statement placeholder)
  • loop else block (Runs if and only if the loop is exited normally without hitting a break)

break statement

The break statement causes an immediate exit from a loop. Because the code that follows it in the loop is not executed if the break is reached, you can also sometimes avoid nesting by including a break.

A Python break statement ends the present loop and instructs the interpreter to starts executing the next statement after the loop. It can be used in both ‘for’ and ‘while’ loops. Besides leading the program to the statement after the loop, a break statement also prevents the execution of the ‘else’statement.

Syntax

break

Flow Diagram

 

Python break statement

Example

while true:
   name = input('Enter name:')
   if name == 'CSE': break
   age = input('Enter age:')
   print('Hello', name, '=', int(age)**2)

Output

 Enter name: xyz
 Enter age: 20
 Hello xyz = 400
 Enter name: CSE

 

continue statement

The continue statement causes an immediate jump to the top of a loop.

It also sometimes lets you avoid statement nesting.

The continue statement brings back program control to the start of the loop. You can use it for both ‘for’ and ‘while’ loops.

Syntax

continue

Flow Diagram

Python continue statement

Example

x = 10
while x:
   x =x-1
   if x % 2 ! = 0: continue
   print(x, end=' ')
 

Output

 8 6 4 2 0