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. The while loop is mostly used in the case where the number of iterations is not known in advance.

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 should be any valid python expression resulting into true or false. The true is any non-zero value.


Python while loop
Python while loop

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

  1. i=1  
  2. number=0  
  3. b=9  
  4. number = int(input("Enter the number?"))  
  5. while i<=10:  
  6.     print("%d X %d = %d \n"%(number,i,number*i));  
  7.     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


;