While is a type of looping statement where the number times of the statement will iterate is decided by the condition of the loop. If the condition is true then the loop will execute otherwise it will terminate and will execute statement after the loop. While is an entry controlled loop where the condition of the loop is tested before entering the loop body. The syntax of a while loop in Python programming language is
while condition: loop body iteration statement
The Infinite while Loop
A while loop becomes infinite loop if the condition in the loop never becomes FALSE. This results in a loop that never ends. Such a loop is called an infinite loop. It can be achieved by making the condition true. If the condition equates to zero it becomes false and the loop will end. The syntax for infinite loop is
while True: or while (1):
Here while is a Python keyword, it is followed by the condition of the while loop and a colon (:). After this line, the loop body is written and is indented with respect to the while statement. The loop body can be a single line statement or can be a block of code.
Indentation of the body will tell python that the block of code is within the while loop and it has to be iterated according to the condition. Python uses indentation as its method or the way of grouping statements. In Python, all the statements which are indented by the same number of spaces after a construct are considered to be a single block of code. The iteration statement in the while loop helps to continue the loop in a particular direction according to the condition i.e. either forward or backward.
# program to print all natural numbers up to 10 n = 1 while( n <= 10 ) : print(n) n = n + 1 # iteration statement
Using else Statement with while loop
We have used else with if statement to test conditions. It plays an important role as a conditional statement. Python also supports to have an else statement along with a looping statement. If the else statement is used with a while loop then the else statement is executed when the condition becomes false in case of the while loop. As we have seen in for loop that else statement is executed when the loop is exhausted iterating over a list of values.
x = 10 while x > 0 : print(x) x = x - 1 else: print("x is now zero")