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.
while expression: 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.
i=1; while i<=10: print(i); i=i+1;
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;
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.
while (1): print("Hi! we are inside the infinite while loop");
var = 1 while var != 2: i = int(input("Enter the number?")) print ("Entered value is %d"%(i))
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.
i=1; while i<=5: print(i) i=i+1; else:print("The while loop exhausted");
i=1; while i<=5: print(i) i=i+1; if(i==3): break; else:print("The while loop exhausted");