Introduction
Syntax:
- while(condition):
- Body of the loop

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

Example 2: Printing table of given number.
- num=int(input("Enter a Number : "))
- i=1
- while(i<=10):
- print(num*i)
- i=i+1

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)
Output:

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:
- #program to check
- #weather the given number is
- #prime number or not
- 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)


Santhakumar MunuswamyPosted Oct 18, 2015, 5:39 AM
Good one
Nilesh JadavPosted Oct 7, 2015, 5:51 AM
Good one