Loop Control Statements

In this tutorial, I will discuss about python important keywords and their use while working with loops in python. These keywords are Break, Continue and Pass. We will also discuss about Loop Else statement which can be used as else after execution of a loop.

Break, Continue, Pass And Loop Else

We have discussed about three main components of python flow of control namely, if-else statements (conditional statements), for loop and while loop statements (looping statements). Now what if we want to alter the flow of the program based on a certain condition when the loop is iterating ?

Python provides different ways to do so in the form of Jump statements (break and continue), pass statement and loop else statement. We are going to look into each of them one by one.

Break and Continue Statements

Python provides us with two statements namely Break and Continue. These are also known as jump statements because they are used to jump of the loop iterations and exit the loop.

Break Statement

The break statement is used in a program, to skip over a part of the code. A break statement terminates the loop it lies within. The execution resumes at the statement following the loop.

Look at the following ways to use break statement :

while test condition:
    statement1
    if condition2 :
        break    # break statement
    statement2
    statement3
# the program flow continues from this statement after it encounters the break statement
statement4   
statement5
for val in sequence:
    statement1
    if condition :
        break    # break statement
    statement2
    statement3
# the program flow continues from this statement after it encounters the break statement
statement4   
statement5

A loop have two ways to end :

  1. If the test expression in while loop evaluates to False then it terminates the while loop and the for loop terminates after it is executed for the last value of sequence. This is normal termination.

  2. If while loop evaluates break statement then it terminates execution even if the test expression is True and the for loop terminates after encountering the break statement even if it has not been executed for every element of the sequence.

Let's have a look at some examples :

Example 1 :

i = 0
while i < 10 :
    print(i)
    if i == 6:
        print("Breaking from while loop")
        break
    i = i+1
print("While loop ended...")
0
1
2
3
4
5
6
Breaking from while loop
While loop ended...

The above example shows how a break statement ends the iteration of while loop even if the test expression evaluates to be True and program control is passed on to the next statement after the loop.

Example 2 :

for i in [0,1,2,3,4,5]:
    print(i)
    if i == 3:
        print("Breaking from for loop")
        break
print("For loop ended...")
0
1
2
3
Breaking from for loop
For loop ended...

The above example shows how a break statement ends the iteration of for loop even if it is not executed for every value of that sequence and the program control is passed on to the next statement after the loop.

Example 3 :

while True:  # this way while loop runs infinitely
    temp = eval(input("Enter temperature in celsius(-1000 to terminate) : "))
    if temp == -1000:
        print("Loop terminanted ...")
        break
    print(temp," celsius is equal to ",9/5*temp+32," Farenheit")
print("Thankyou !!!")
Enter temperature in celsius(-1000 to terminate) : 25
25  celsius is equal to  77.0  Farenheit
Enter temperature in celsius(-1000 to terminate) : 76
76  celsius is equal to  168.8  Farenheit
Enter temperature in celsius(-1000 to terminate) : -1000
Loop terminanted ...
Thankyou !!!

In the above example we let the user enter temperature in Celsius and convert it into Fahrenheit. Notice that it is an infinite loop which only gets terminated of we enter -1000 as written in the condition which leads to break statement.

Continue Statement

Continue statement works similar to break the difference is that break terminates the loop completely whereas the continue statement only terminates the current iteration. Once encountered the continue statement skips rest of the statements and forces the next iteration of the loop to take place.

Look at the following ways to use continue statement :

while test condition:  
    # the program flow continues from next iteration after it encounters the continue statement
    statement1
    if condition2 :
        continue    #continue statement
    statement2
    statement3
statement4
for val in sequence:  
    # the program flow continues from next iteration after it encounters the continue statement
    statement1
    if condition :
        continue    #continue statement
    statement2
    statement3
statement4  

The continue statement is used when we want to skip the loop only for some values and then continue execution of the loop for next values.

Let's have a look at some examples :

Example 1 :

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

print("\nEnd of loop")
2 4 6 8 10 
End of loop

In the above code, we skip the odd values using continue statement and print the even numbers. Note that we have put the update expression (x = x+1) before the condition of continue statement so that the loop will execute properly.

Example 2 :

for i in range(10):
    if i == 2 or i == 4:
        continue
    print(i, end = ' ')
0 1 3 5 6 7 8 9 

In the above code, we skip the for loop when i has value 2 or 4 and the loop executes normally for rest of the values.

Pass Statement

The pass statement in python is a non-operative placeholder which is generally used when the syntax requires a statement, but we have nothing to write.
When we want to code an infinite loop which does nothing this pass statement can be used as a placeholder in place of loop body as follows:

while True:
    pass

Pass statement is also used with functions, classes and other which we will look into later.

Loop Else Statement

We have seen the use of else clause in python with if, but it can also be used with looping statements i.e. for and while.

The else clause with any loop (for or while) executes only when the loop terminates normally.

It means when the test expression evaluates to False in case of while loop or for loop has executed the last value from the sequence but not when break statement terminates the loop.

Let's see how the syntax and flow of program works.

for val in sequence:
    #block of statements
else:        #executes when for loop executes for all values in sequence.
    statement1
statement2
while test condition:
    #block of statements
else:       #executes when test condition evaluates to be False.
    statement1
statement2

Let's have a look at some examples :

Example 1 :

for i in [1,2,3,4] :
    print("Element is : ",i)
else:
    print("Loop terminated successfully...")   
Element is :  1
Element is :  2
Element is :  3
Element is :  4
Loop terminated successfully...

Note that the for loop executes for every value of the sequence and terminates properly then the else block is executed.

Example 2 :

a = 0
while a < 5:
    print("Element = ", a)
    a = a + 1
else:
    print("Loop terminated successfully...")
Element =  0
Element =  1
Element =  2
Element =  3
Element =  4
Loop terminated successfully...

Similar to the for loop the while loop executes until the test condition evaluates to be False, after that the else block is executed.

Conclusion

In this tutorial, we have discussed about break, continue and pass keywords and their use with the loop statements in python.We have also seen the use of loop else statement with for and while loops in python.

If you have any questions about loop control statements,please comment below also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment