While Loop in Python Programming | Python Programming
While Loop in Python: While Loop is used to execute a block of statements again and again or we can say that repeatedly until our given condition is True. Previously we learnt about for loop, both for loop and while loop used for the same purpose. While loop stops execution when the condition inside while loop returns False.
Now the question arises, that if the purpose of while and for loop is the same then what is the use of while loop. Difference between for loop and while loop is that, when we are not sure of the numbers that how much time or long loop execute, in that case, we use while loop.
And when we are sure about the numbers that how many times we need to execute the loop, in that case, we use for loop.
Flow Diagram of While Loop:
Execution Flow of While Loop: Code or statements inside while loop will execute only if the condition is given in while loop is True. If it is False then code/statements do not execute and the loop is terminated.
- The condition given inside the while is checked, if it is True code executes else the loop will be terminated.
- If the condition given is True, then the statements will be executed successfully.
#While loop Syntax while(condition): #statements
Example: Previously we solved one question using for loop, now we will solve the same question but using while loop.
-> Write a Program to print multiples of 2 using while loop
#While loop example x = 0 while(x < 11): print(x*2) x += 1 # output # 0 # 2 # 4 # 6 # 8 # 10
What is nested while loop in Python?
Nested while loop: While loop used inside other while loop is called nested while loop. Below is the given example on nested while loop.
#nested while loop example x = 0 y = 0 while(x > 3): while(y>3): print(x +"-"+y) # output # 0 - 0 # 0 - 1 # 0 - 2 # 1 - 0 # 1 - 1 # 1 - 2 # 2 - 0 # 2 - 1 # 2 - 2
Note: If the condition inside while remains always true, then in that case an infinite loop will execute that will never stop execution.
Example of infinite while loop:
#Infinite while loop example x = 0 while(x==0): print("Pythonlobby") # output # Pythonlobby # Pythonlobby # Pythonlobby # .... # .... # ....infinite
What is the difference between for loop and while loop in Python?
Both for loop and while loop returns the same result and used for iteration. But the execution of for loop depends upon the item it has to iterate and on the other side iteration of while depends upon the True or False condition. When we are sure about the numbers that how many time we need to run the loop then we prefer to use for loop and if the number is not known then we use while loop.
Example 1: WAP to display factorial of a number using for loop.
1). Using For loop()
fact = 1 for i in range(1,6): fact = fact * i print(fact) # output # 120
Example 2: WAP to display factorial of a number using while loop.
2). Using While loop()
n = 5 fact = 1 while(n): fact = fact * n n = n-1 print(fact) # output # 120