Introduction
In this article, we will discuss while loop in Python. A while loop is a control flow statement which checks the condition, and the condition is true then executes a block of code again and again.
Syntax:
- while(condition):
- Body of the loop
Flow Chart: The flow chart of while loop is given as follows:
In the above flow chart you can see whenever control of the program enters into the loop then, first of all on the entry time it will check some condition. If the condition will become true then only it will go inside the loop and execute the body of the loop and again it will check after first execution and if the condition is again true then it will again execute the body of the loop. This iteration goes continuously while the condition is true. Whenever the condition will be false, the control of the program comes out.
Example: Printing 1 to 20.
- i=1
- while(i<=20):
- print(i)
- i=i+1
Output:
Example 2: Printing table of given number.
- num=int(input("Enter a Number : "))
- i=1
- while(i<=10):
- print(num*i)
- i=i+1
Output:
Example 3: Printing reverse of a number.
- num = int(input("Enter a Number : "))
- rev = 0
- while(num != 0):
- rem = num % 10
- rev = rev * 10 + rem
- num = int(num / 10)
- print(rev)
While loop with else
In python, we can also execute while loop with else part. While loop works the same as a normal while loop, but whenever while loop condition will be false it's else part will execute.
Note: else part will only execute when while loop condition will be false. If while loop will be terminated by break statement then while loop's else part never executes.
Example 4:
-
-
-
- num = int(input("Enter a Number : "))
- i=2;
- while(i<num):
- if(num%i==0):
- print("%d is not a prime number..."%num)
- break
- i=i+1
- else:
- print("%d is a prime number..."%num)
Output: