Python While Loop
Introduction
Python While Loop
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
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
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)
Conclusion
In the next chapter, we will learn to use Python for loop
Author
Sourabh Somani
Tech Writter
47.6k
10.9m