While Loop in Python

Introduction

 
In this article, I will explain the while loop in Python. In this loop, an announcement is run once if its condition evaluates to True, and never runs if it evaluates to False. A while statement is similar, except it can be run one or more times. The statements inside it are time and again executed, as long as the circumstance holds. Once False, the next code will be executed.
 
While Loop In Python
  1. SyntaxWhile expression:    
  2.       print (while statement)   
Example
 
Simple program for a while loop:
  1. i = 1    
  2. while i < 10:    
  3.   print(i)    
  4.   i += 1   
Output
 
Remember that i's value is 10, so the block of code will be executed 10 times.
 
While Loop In Python
 

While Loop and Break Statement

 
We can stop the loop with the break declaration although the while condition is true.
 
Syntax
  1. While expression:    
  2.      if condition:    
  3.              break   
Example
 
Here's a simple program for the while loop and break statement.
  1. i = 1    
  2. while i < 10:    
  3.   print(i)    
  4.   if (i == 5):    
  5.     break    
  6.   i += 1   
Output
 
Note that after number 5, there's no display in the output screen.
 
While Loop In Python
 

While Loop and Continue Statement

 
The continue statement is used to leave a sum statement and it continues with the next statement.
 
  1. SyntaxWhile expression:    
  2.        if condition:    
  3.             continue   
Example
 
Simple program for a while loop and condition statement.
  1. i = 0    
  2. while i < 10:    
  3.   i += 1    
  4.   if i == 5:    
  5.     continue    
  6.   print(i)   
Output
 
Note that the number 5 is missing in the output.
 
While Loop In Python
 

While Loop and Pass Statement

 
The pass statement is used to write an empty loop statement. Pass is also used for empty control statements.
 
Syntax
  1. While expression:    
  2.       if condition:    
  3.             pass    
Example
 
Here's a simple program for a while loop and pass statement.
  1. i = 0    
  2. while i < 10:    
  3.   i += 1    
  4.   if i == 5:    
  5.     pass    
  6.   print(i)   
Output
 
The pass statement does not change anything.
 
While Loop In Python
 

While Loop and Else Statement

 
In the else statement, we will run a block of code once while the condition false.
 
  1. SyntaxWhile expression:    
  2.      print (while statement)    
  3. else:    
  4.      print (else statement)  
Example
 
Simple program for a while loop and else statement.
  1. i = 1    
  2. while i < 10:    
  3.   print(i)    
  4.   i += 1    
  5. else:    
  6.   print ("i is less than 10")    
Output
 
Prints a message one time while the condition is false.
 
While Loop In Python
 

Conclusion

 
In this article, we have seen the while loop in Python. I hope this article was useful to you. Thanks for reading!