Featured

    Featured Posts

While loop In Python

while loop:
§  If we want to execute a group of statements multiple times until some condition false, then we should go for while loop.
Syntax:
          while condition:
                   body


§  Write a program to display first n natural numbers.
n=int(input('enter number'))
i=1
while i<=n:
    print(i)
    i=i+1
Output:
enter number5
1
2
3
4
5

Note-
·        In implementation when we need to extract last digit from the given data than go for %10. If we require to remove last digit from the given number than go for divide by /10
a= 158%10  à 8
a=123%10 à 3
a=97%10 à 7
a=5%10 à 5
Note-
If the numerator value is less than of denominator value than if it is modular operator returns numerator value.
a= 158//10  à 15
a=123//10 à 12
a=97//10 à 9
a=5//10 à 0
Note-
If the numerator value is less than of denominator value than if it is division operator returns zero.

§  Write a program to display the sum of all digits to given number.
n=int(input('enter number'))
sum=0
while n>0:
    d=n%10
    sum=sum+d
    n=n//10
print('Sum of Digits = ',sum)
Output:
enter number123
Sum of Digits =  6

§  Write a program to display the reverse of a given number.
n=int(input('enter number'))
rev=0
while n>0:
    d=n%10
    rev=rev*10+d
    n=n//10
print('Reverse of Number = ',rev)
Output:
enter number123
Reverse of Number =  321



§  Write a program to check whether given number is an Armstrong or not.
Armstrong number is a number that is equal to the sum of cubes of its digits.
 For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
 Let's try to understand why 153 is an Armstrong number.
153 = (1*1*1)+(5*5*5)+(3*3*3)  
where:  
(1*1*1)=1  
(5*5*5)=125  
(3*3*3)=27  
So:  
1+125+27=153  

n=int(input('enter number'))
sum=0
temp=n
while n>0:
    #Extracting the last digit from given number
    d=n%10
    sum=sum+(d**3)
    n=n//10
if temp==sum:
    print(temp," is a ArmStrong Number")
else:
    print(temp," is a ArmStrong Number")

Output:
enter number153
153  is a ArmStrong Number

author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews