The while loop provide us the utility to execute a particular set of statements repeatedly until the required condition is fulfilled.
How it works :
Firstly, Python interpreter looks out for the condition, if the given condition is True, then it will execute all the statements inside the loop. Once all the statements gets executed, it will go back and check the condition again. It will keep doing so, as long as condition remains True. And when this condition gets false, control is send out of the loop.
Let us code an example to perform the implementation of while loop.
Program : Program to display the counting from 1 to 10 using while loop.
i=1 while(i<=10): print(i,end=' ') i+=1
1 2 3 4 5 6 7 8 9 10
Let us consider one program using while loop
Program : To evaluate the sum of digits of a number.
n=23417 sum=0 while(n>0): rem=n%10 sum=sum+rem n//=10 print("Sum of digits : ",sum)
Sum of digits : 17
Let the number be 23417 so our task is to evaluate 2+3+4+1+7. We can do so by finding the remainder of a number(adding it to sum),divide it with 10 until the number gets 0. For this we need a 'while' loop which will run till 'n>0'.In each iteration we perform three steps :
1. rem=n%10; //rem=23417%10=7
2. sum=sum+rem; //sum=7
3. n=n/10; //num=23417/10=2341
Hence on repeating these steps(till n>0), we get the sum of digits of a number.
This is how while loop works.