When an instruction is repeating till a condition is satisfying is known as loop.
That means the repetition of an instruction is known as loop.
When the condition will not satisfy then the loop will terminate.
Python supports two types of loop, such as while loop and for loop.
The general form is:
while b:
statement1
statement2
----------- #loop body
statementn
b : anything that should be a boolean value(True / False)
Here first we evaluate b, if b is True then loop body will execute. That means once a condition is becoming True, loop body is executing. This is called one iteration. After executing loop body, the control will go to condition expression, again the condition expression will evaluate, if it will be True then again loop body will execute. It will repeat till the condition is becoming False. When the conditional section becoming False then the loop will terminate.
Flow chart of python while loop:
#program to display the numbers from 1 to 5
#initialize variables
x=1
y=5
while x<=y:
print(x)
x+=1
output
1
2
3
4
5
Let’s see how the control treat the program like:
Variable Condition: x <= y Loop Body execute
x=1
y= 5 True 1 is printed. x is increased to 2.
x=2
y = 5 True 2 is printed. x is increased to 3.
x=3
y = 5 True 3 is printed. x is increased to 4.
x=4
n = 5 True 4 is printed. x is increased to 5.
x=5
n = 5 True 5 is printed. x is increased to 6.
x=6
n = 5 False The loop is terminated.
#Python program to find the reverse of a number and check whether the no is palindrome or not
n=int(input("enter the number"))
reverse=0
number=n
while n!=0:
num=n%10
reverse=reverse * 10 + num
n=n//10
print("the reverse is:",reverse)
if number==reverse:
print("number is palindrome")
else:
print("number is not palindrome")
output
enter the number121
the reverse is: 121
number is palindrome
#python program to find the sum of numbers until the user enters zero
total_sum=0
number=int(input("enter a number:"))
#add numbers until number is zero
while number!=0:
total_sum+=number #total_sum=total_sum+number
#take integer input again
number=int(input("enter a number:"))
print("total sum=",total_sum)
output
enter a number:20
enter a number:10
enter a number:-5
enter a number:0
total sum= 25
#infinite while loop in python
# If the condition of a loop is always True, the loop runs for infinite times.
number=29
while number>18:
print("welcome")
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc