Loops

Lesson Progress
0% Complete

In general, statements are executed sequentially one block of code after another. We use loops to execute a block of code several number of times.

Python provides the following types of loops to handle looping requirements:

  • For loop
  • While loop
  • Nested loops

While loop

In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.

Syntax:

python">while expression:
  statement(s)

Example

python"># Program to illustrate while loop 
count = 0 
while ( count < 9):
 print "The count is: ",
 count count = count + 1
 print "Goodbye!"

Output:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1. 

For loop

The for statement in Python has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:
   statements(s)

The range() function

The built-in function range() is the right function to iterate over a sequence of numbers. It generates an iterator of arithmetic progressions.

Example to illustrate for loop using range():

for var in range(0,10):
    print var

Output:

0
1
2
3
4
5
6
7
8
9

Here, the print statement will be executed from 0 to 9

Another example to loop through a list

fruits = [“apple”, “banana”, “mango”]

for fruit in fruits:
    print "Current fruit is: ", fruit

print “Goodbye!” 

Output:

The current fruit is: apple
The current fruit is: banana
The current fruit is: mango
Goodbye!

Nested loops

In Python, you can place one loop inside another loop. 

Syntax for loop

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Syntax while loop

while expression:
   while expression:
      statement(s)
   statement(s)

Example to illustrate nested for loops in Python 

# Python program to illustrate nested for loops in Python 
import sys
for i in range(1, 5): 
    for j in range(i): 
        print(i, end=' ') 
print() 

Output

1 
2 2 
3 3 3 
4 4 4 4

The print() function inner loop has end=’ ‘ which appends a space instead of default newline. Hence, the numbers will appear in one row.Last print() will be executed at the end of inner for loop.

Note: You can put any type of loop inside another loop. For example, a while loop can be inside a for loop and vice versa.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

Break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop. Used for premature termination of a loop.

Example

for letter in ‘Python’:
    if letter ==  ‘h’
    break
print “Current letter is:  “, letter

Output:

Current letter is:  P
Current letter is:  y
Current letter is:  t

In the example, the code will execute until it encounters letter ‘h’ then terminates and leaves the loop.

Continue statement

It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating i.e It returns the control to the beginning of the loop.

Example: To print even numbers only:

for num in range(0, 10):
    if num%2 == 0:
       print “Found an even number: “, num
       continue

Output:

Found an even number: 0
Found an even number: 2
Found an even number: 4
Found an even number: 6
Found an even number: 8

Here, the program loops from 0 to 9 and prints even numbers only, skipping any odd number

Pass statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

while True:
    pass