While Loop in Python
while loop is used to execute a block of statements repeatedly until a given condition is true. And when the condition becomes false, it will skip the loop and, the line immediately after the loop is executed.
Syntax:
while expression:
statement(s)
Example:
Python Program to illustrate while loop
count = 1 # initially count = 0
while count <= 5 : # count should be <= 5
print('The count is:', count) # prints the count value
count = count + 1 # increments the count value by 1
print("End of the program") # executes this statement
Output: The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 End of the program
In the above program, the while block consist of printing the count value and incrementing the count value by 1.
The while block will be executed till the count is less than or equal to 5.
When ever the count value is 6, it will skip the while block and executes the statement followed by while block.
Example:
Python Program to find number of digits in a given number using While loop
n = int(input("enter a no. ")) # read a number from user
nod=0 # assign 0 to nod
while n>0: # checks whether n > 0 or not
nod = nod + 1 # increment nod by 1
n = n // 10 # removes units digit from n & assign that to n
print(nod) # prints nod value
Output: enter a no. 159 3
Python Program to find whether the given number is palindrome or not using While Loop
n = int(input("enter a no. \n")) # reads a no. from user
n1 = n # assign n to n1
rev=0 # assign 0 to rev
while n>0: # checks whether n > 0 or not
rev = rev *10 + n%10 # multiplying 10 with rev & adds that to #remainder
n = n // 10 # removes units digit from n & assign that to n
if n1==rev: # checking n1 with rev
print("palindrome ")
else:
print("not palindrome ")
Output: enter a no. 252 palindrome
Example:
Python Program to find whether the given number is Armstrong or not.
Armstrong numbers are those numbers which are equal to the sum of the cubes of each digit of the same number.
153 = 1^3 + 5^3 + 3^3 = 153
Example Armstrong numbers
1,2,3,4,5,6,7,8,9,153,370,371,407,1634, etc. are Armstrong numbers
# Program to find whether the given number is Armstrong no. or not.
n = int(input("enter a no. \n ")) # reads a no. from user
n1=n # assign n to n1
n2=n # assign n to n2
nod,sum=0,0 # assign 0 to nod & sum
while n>0: # this loop is used to find no.of digits in a given no.
nod =nod+1
n=n//10
while n1>0: # checks whether n1 > 0 or not
r=n1%10 # finds remainder
sum=sum+pow(r,nod) # power of a digit is added to previous sum
n1=n1//10 # removes units digit from n1 & assign that to n1
if sum==n2: # checking whether sum == n2 or not
print("Armstrong no.")
else:
print("not Armstrong no.")
Output enter a no.
371
Armstrong no.