Loops in Python programming language

 

Loops in Python programming language

The flow of the programs written in any programming language is sequential by default one after one statement are executed. But sometimes the requirements are different and we need to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of times. Sometimes we need to repeat a specific code 1000 or more times. 

For this purpose, The programming languages provide various types of loops which are capable of repeating some specific code several numbers of times. Consider the following diagram to understand the working of a loop statement.

 

Why we use loops in python?

The loops in python or any other programming language solve the complex problem of repeating code multiple times in an easy way. Loops allow us to change the flow of the program so that writing the same code, again and again, we can repeat the same code for a finite number of times. For example, if we need to print a line 10 times or more then using of the print statement 10 or more times, we can print that inside a loop that runs up to 10 or more iterations.

Advantages of loops

There are the following advantages of loops in Python.

  1. It provides code re-usability.
  2. Writing the same code, again and again, Loops solve this problem.
  3. Using loops, we can traverse over the elements of data structures ( lists, tuples, dictionaries).

There are the following loop statements in Python.

Loop Statement

Description

for loop

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied.  It is better to use for loop if the number of iteration is known in advance.

while loop

The while loop is to be used in the scenario where we don't know the number of iterations in advance. The block of code written in while loop is executed until the condition in the while loop is satisfied. It is also called a pre-tested loop.

do-while loop

The do-while loop continues until a given condition satisfies. It is also called post tested loop. do-while loop is used when it is required to execute the loop at least once.

 

The print() function used to print something and print() function knows to inserts a new line or break at the end

The print Function

The big change in Python 3 is how the print() function is used. In python 3 the use of parenthesis () with print function is now mandatory you must write it print(). It was optional in Python 2.

print"Hello World"#is acceptable in Python 2
print("Hello World")# in Python 3

The print() function inserts a new line at the end, by default In Python 3, "end =' '" appends space instead of a newline.

Python for loop

The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.

For loop syntax in python

1.      for iterating_var in sequence:  

2.          statement(s)  

 

Example 1

1.      i=1  

2.   number=int(input("Enter any number"))  

3.      for i in range(0,5):   #Range iterate between 0 and 10

4.          print(i)  

Output:

0 1 2 3 4 

Example 2

1.      i=1;  

2.      num = int(input("Enter a number:"));  

3.      for i in range(1,11):  

4.          print("%d X %d = %d"%(num,i,num*i));  

Output:

Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Nested for loop in python

Loop inside another loop is a nested loop. In python, we can code nested loops. The inner loop is executed n number of times for every iteration of the outer loop. Example of nested loops in python is

1.      for iterating_var1 in sequence:  

2.          for iterating_var2 in sequence:  

3.              #block of statements   

4.      #Other statements  

Example 1

1.      number = int(input("Enter a number"))  

2.      i,j=0,0 #Assignment of values to i and j  

3.      for i in range(0,n):  

4.          print()  

5.          for j in range(0,i+1):  

6.              print("*")  

Output:

Enter a number 5
*
**
***
****
*****

 Using else statement with for loop

Unlike other languages like C, C++, or Java, python allows us to use the else statement with the for loop which can be executed only when all the iterations are exhausted. Here, we must notice that if the loop contains any of the break statement then the else statement will not be executed.

Example 1

1.      for i in range(0,5):  

2.          print(i)  

3.      else:

pr       print("Else section");  

In the above example, for loop is executed completely since there is no break statement in the loop. When for loop complete execution then else statement will be executed.

Output:

0
1
2
3
4

Else Section

Example 2

1.      for i in range(0,5):  

2.          print(i)  

3.          break;  

4.      else:print("for loop is exhausted");  

5.      print("Else statement")  

In the above example, the loop is broken due to break statement therefore the else statement will not be executed. The statement present immediate next to else block will be executed.

Output:

0

The loop is broken due to break statement...came out of loop

 

Python while loop

The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed as long as the given condition is true.

It can be viewed as a repeating if statement. When the number of iterations is unknown then while loop are used.

The syntax is given below.

1.    while expression:  

2.        statements  

Here, the statements can be a single statement or the group of statements. The expression passed in while loop parameter should be any valid python expression resulting into true or false. The true is any non-zero value.

 

Example 1

1.    i=1;  

2.    while i<=10:  

3.        print(i);  

4.        i=i+1;  

Output:

1
2
3
4
5
6
7
8
9
10

Example 2

i=1  

number=0  

b=9  

number = int(input("Enter the number?"))  

while i<=10:  

    print("%d X %d = %d \n"%(number,i,number*i));  

    i = i+1;  

Output:

Enter the number?10
 
10 X 1 = 10 
 
10 X 2 = 20 
 
10 X 3 = 30 
 
10 X 4 = 40 
 
10 X 5 = 50 
 
10 X 6 = 60 
 
10 X 7 = 70 
 
10 X 8 = 80 
 
10 X 9 = 90 
 
10 X 10 = 100 

Infinite while loop

If the condition given in the while loop never becomes false then the while loop will never terminate and result into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.

Example 1

1.    while (1):  

2.        print("Hi! we are inside the infinite while loop");  

Output:

Hi! we are inside the infinite while loop
(infinite times)

Example 2

1.    var = 1  

2.    while var != 2:  

3.        i = int(input("Enter the number?"))  

4.        print ("Entered value is %d"%(i))  

Output:

Enter the number?102
Entered value is 102
Enter the number?102
Entered value is 102
Enter the number?103
Entered value is 103
Enter the number?103
(infinite loop)

Using else with Python while loop

Python enables us to use the while loop with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed and the statement present after else block will be executed.

Consider the following example.

1.    i=1;  

2.    while i<=5:  

3.        print(i)  

4.        i=i+1;  

5.    else:print("The while loop exhausted");  

Output:

1
2
3
4
5
The while loop exhausted

Example 2

1.    i=1;  

2.    while i<=5:  

3.        print(i)  

4.        i=i+1;  

5.        if(i==3):  

6.            break;  

7.    else:print("The while loop exhausted");  

Output:

1
2

Python break statement

The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given condition.

The syntax of the break is given below.

1.    #loop statements  

2.    break;   

 

 

Example 2

1.    str = "python"  

2.    for i in str:  

3.        if i == 'o':  

4.            break  

5.        print(i);  

Output:

p
y
t
h

 

Example 3: break statement with while loop

1.    i = 0;  

2.    while 1:  

3.        print(i," ",end=""),  

4.        i=i+1;  

5.        if i == 10:  

6.            break;  

7.    print("came out of while loop");  

Output:

0  1  2  3  4  5  6  7  8  9  came out of while loop

 

Example 3: break statement with while loop

1.   i = 0;  

2.   while 1:  

3.       print(i," ",end=""),  

4.       i=i+1;  

5.       if i == 10:  

6.           break;  

7.   print("came out of while loop");  

Output:

0  1  2  3  4  5  6  7  8  9  came out of while loop

Example 3

1.   n=2  

2.   while 1:  

3.       i=1;  

4.       while i<=10:  

5.           print("%d X %d = %d\n"%(n,i,n*i));  

6.           i = i+1;  

7.       choice = int(input("Do you 

want to continue printing 

the table, press 0 for no?"))  

8.       if choice == 0:  

9.           break;      

10.                    n=n+1  

Output:

Pass Statement

The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a statement is syntactically needed but we don?t want to use any executable statement at its place.

For example, it can be used while overriding a parent class method in the subclass but don't want to give its specific implementation in the subclass.

Pass is also used where the code will be written somewhere but not yet written in the program file.

The syntax of the pass statement is given below.

 

 

Example

1.    list = [1,2,3,4,5]  

2.    flag = 0  

3.    for i in list:  

4.        print("Current element:",i,end=" ");  

5.        if i==3:  

6.            pass;  

7.            print("\nWe are inside pass block\n");  

8.            flag = 1;  

9.        if flag==1:  

10.         print("\nCame out of pass\n");  

11.         flag=0;  

Output:

Current element: 1 Current element: 2 Current element: 3 
We are inside pass block
 
 
Came out of pass
 
Current element: 4 Current element: 5 

 

Python Pass

In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code, the pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.

Python Pass Syntax

1.    pass  

Python Pass Example

1.    for i in [1,2,3,4,5]:  

2.        if i==3:  

3.            pass  

4.            print "Pass when value is",i  

5.        print i,  

Output:

1.    >>>   

2.    1 2 Pass when value is 3  

3.    3 4 5  

4.    >>>  

 

 

Enjoyed this article? Stay informed by joining our newsletter!

Comments
Sajjad Ahmad - Jan 26, 2020, 10:05 AM - Add Reply

nice dear.thanks

You must be logged in to post a comment.

You must be logged in to post a comment.

Related Articles
About Author