The while loop provides a mechanism to repeat one or more statements while a particular condition is True.
The syntax of while loop is shown below.
statement x while (condition): statement block statement y
Note in the while loop, the condition is tested before any of the statements in the statement block is executed. If the condition is True, only then the statement will be executed otherwise if the condition is False, then the control will jump to statement y, that is the immediate statement outside the while loop block.
It is important to constantly update the condition of the while loop. It is this condition which determines when the loop will end. The while loop will execute as long as the condition is True. Note that if the condition is never updated and the condition never becomes False, then the computer will run into an infinite loop which is never desirable.
A while loop is also referred to as a top-checking loop since control condition is placed as the first line of the code. If the condition evaluates to False, then the statement enclosed in the loop are never executed.
Let’s write a program to print the first 10 numbers using a while loop.
i = 0 while (i <= 10): print(i, end=" ") i = i + 1
#output 0 1 2 3 4 5 6 7 8 9 10
Note that initially i = 0 and is less than 10, that is the condition is True, so in the while loop the value of i is printed and then i is increment by 1. Then again the condition is checked. Since i = 2 the i is printed again and i is incremented by 1. This happens until i becomes greater than 10. When I becomes greater than 10, the while condition becomes False and the program exit the while loop.
Let’s write a program that calculates the sum of numbers from m to n.
m = int(input("Enter the value of m: ")) n = int(input("Enter the value of n: ")) s = 0 while (m <= n): s = s + m m = m + 1 print("Sum is : ", s)
#output Enter the value of m: 2 Enter the value of n: 10 Sum is : 54