while loop 

Loop executes the same statement over and over again.Indentation has great importance in looping.
while Loop is used until the condition is true, the statement executes and the iteration of the loop when the condition becomes false; stops.



Syntax for while Loop in Python

  • while (expression):
  • while_statement (s)


Example for while loop

Source Code:


x = 0

while (x <10):
    print ("Value x is", x)
    x = x + 1

Output:

Value x is 0
Value x is 1
Value x is 2
Value x is 3
Value x is 4
Value x is 5
Value x is 6
Value x is 7
Value x is 8
Value x is 9

while loop

while Loop with else Statement in Python

The relation of while Loop else is made. As long as the condition is true, while the statement of the while loop keeps iterating and the condition is false then the control pass is passed and executing the else statement.

Source Code:


x = 0

while (x <5):
    print ("Value of x is", x);
    x = x + 1
else:
    print ("Out of Loop");

Output:

Value of x is 0
Value of x is 1
Value of x is 2
Value of x is 3
Value of x is 4
Out of loop

while loop with else statement

infinite loop in python

As long as the expression of while is 'True', he keeps executing his statement. The condition on the example is not being false at all, that is why infinite times; The statement is being executed.

Source Code:

while (True): #expression is always true
   print ("Hello")
   print("Hii")


Output:

Hello
Hii
Hello
Hii
Hello
Hii
Hello
Hii
Hello
Hii
Hello
Hii


infinite loop