Loops in Python

In a vast majority of  programming languages, a block of codes  are executed  in the order  starting from the first statement and Python programming is not an exception.  When a function in a program is executed in Python, it is the same.  The first statement is executed first, followed by the next one and so on.

Whenever there is a need to execute a block of code multiple times until certain condition is met,  a loop statement is used. A loop statement allows to execute a statement or a group of statements a number of times.

In Python we have three types of loops  for, while and do-while.  Also, there is nested loops, break statements to break the loop. The details of its syntax and usage in python programming are as follows.




1) The “for” loop:

 Executes  a  sequence of statements iteratively.

1
2
3
4
5
6
#syntax
for <Iterating_variable> in <sequence>;
    # statements after an indentation
    # these statements will be repeated inside the for loop

# this comment is outside the for loop

An example of “for” loops in Python :

1) a) The range() function used in for loop :

The range() function is a built-in function that is used to iterate over a sequence of numbers.  This function is used to  generate an iterator of arithmetic progression.

  • range(n): generates a set of whole numbers starting from 0 to (n-1).
  • range(start, stop): generates a set of whole numbers starting from start to stop-1.
  • range(start, stop, step_size): The default step_size is 1.By specifying step-size we can generate numbers having the difference of step_size.

How to use range in for-loops in Python:


1
2
3
4
5
The output will be :
0
1
2
3

1) b) The “<element> in <list>” way in for loop :

How to use “<element> in <list> loop :


1
2
3
4
When  the above code is executed, the result is  
cursor points to : C
cursor points to : a
cursor points to : t

Thus, for loops in Python allow you to iterate through every character in a given string.

Here’s another example:


1
2
3
4
When  the above code is executed, the result is:
Item name : pen
Item name : pencil
Item name : sharpener

1) c) Looping a sequence by Indexing:

This is an alternative way of iterating through an item list by indexing the items in sequence.


1
2
3
4
5
6
The output will be :
The stationary in selection is : pen
The stationary in selection is : pencil
The stationary in selection is : sharpener

#Please note len() is a built-in function that gives the total number of elements in the tuple and the range() function gives us the actual sequence to iterate over.



2) The “while” loop:

Similar to “for”  loop,  while statement is  also used to iterate through a statement or a section of codes as long as the condition (expression) defined in the statement is true. Precisely, the boolean condition which is either  TRUE or FALSE  is checked  before  the statements are executed in the loop.

Here the count will be increased by 7 until its no longer greater than 50.

2) a) “Else” statements in For Loops and While loops:

In For loops, the else statement is optional. If it is used, the else block is executed only if the loop completes execution without being terminated by a break statement.

In While loop, else statement is executed when the while-condition becomes false.

In essence we have the following:

1
2
3
4
5
6
7
8
9
10
11
for condition:
    # execute these statements
else :
   # execute these statements only if the loop
   # exited normally without a break statement

while condition:
    # execute these statements
else :
    # execute these statements only if the loop
    # exited normally without a break statement



3) Nested Loops:

When there is one or more loops inside for loop or While loop or do… while  loop,  they are called nested loops.  Python programming language allows nested loops.

1
2
3
4
5
6
7
8
9
for <iterating_var> in  <sequence>:
    for <iterating_var> in <sequence>
        # these statements execute in loop#2
    # these statements execute in loop#1

while expression:
    while expression:
    # these statements execute in loop#2
    # these statements execute in loop#1

A For loop can be inside a while loop or a while loop can be nested inside a for loop.




4) Loop Control Statements:

break statement  : Terminates the loop and transfers execution to the statement immediately following the loop. It can be used both in for and while loops.

Syntax : break

continue statement : Causes the loop to skip the remainder of its body and it immediately retest its condition prior to reiterating.

Syntax :   continue

pass statement :  In Python, pass statement is used when a statement is required syntactically but we do not actually want to execute any command or code. In other words, you don’t really have any processing that needs to be done inside the loop. The Python interpreter will “pass on” to the next line of code.

Syntax :   pass

Here’s are examples showing the use of a break statement:


1
2
3
4
5
#The output will be:
string is currently: R
string is currently: o
string is currently: s
The loop exited at str = s

Here’s another example of a break statement:

Can you guess the output of the above program?


1
2
3
4
#The output will be:
Value of a is :  7
Value of a is :  6
The value of a = 5

Loops in Python, allow us to exercise a lot of control over the flow of execution and are critical for writing any program.


Leave a Reply

Your email address will not be published. Required fields are marked *