The while loop in Python provide us the utility to execute a particular set of statements repeatedly until the required condition is fulfilled.
Syntax
while(conditions):
Statements
#Fun_Facts about Python ‘while’ loop
- Python allows the concept of nested-while loops.
- We can use for loop inside while loop and vice versa.
- We do have concept of while-else loop in Python.
- while loop supports range() function.
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
# loop to print counting from 1 to 10
while i <= 10:
print(i, end=' ')
i += 1
O/P :
1 2 3 4 5 6 7 8 9 10
Let us consider one more program using while loop
Program : To evaluate the sum of digits of a number.
n = 23417
sums = 0
# loop to traverse each digit of a number
while n > 0:
# finding remainder when number is divided by 10
rem = n % 10
# adding the remainder obtained
sums = sums + rem
# dividing the number by 10 to access next digit of a number
n //= 10
print("Sum of digits : ", sums)
O/P :
Sum of digits : 17
Explanation
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.
Hope you now got the complete picture.
Do you know ?
We can make use of continue statements to skip the current iteration of loop, pass statements to simply pass the iteration, or even break statements to pull the control out of the loop for a given condition, all inside while loop. We will see them in upcoming lessons.
Cook This !
Write a Python program to check whether a given year is a leap year or not. Try to take the input from the user itself.
That’s all, see you in the next lecture.