Python Program to Check Armstrong Number

By | October 11, 2019

Python Program to Check Armstrong Number Here you can see a complicated way of writing program this program can also be written in a simple way

But in order to add more concept I wrote this way

In first line you can see a print statement which ask an input from user

In second line with the help of inbuilt function input()  program takes input from user and stored in variable i here.

In second line remember one thing that whatever user has entered it is stored in variable i as an string because input() function takes input is in string format

In third line we convert our value which is stored in variable i as a string to integer value by typecasting and stored this integer value in num variable we will tell you later on why we have done this

In fifth line we are calculating the length of i in which a string value is stored and we can only calculate length of a string not an integer.

Now come to point user is asked to enter a number but our program take this value as a string

Let us take an example user has entered 153

Now this value stored in variable i as a string like this “153”

Now we need to find to calculate the length of this variable which is stored in i to len you can see it in line five

Now we use while loop here

While loop will run till num does not equal to 0, value =Num%10  will hold only remainder



 Copy and try yourself

print("Enter a number which you want to find armstron number")
i = input()
num = int(i)
b=num
len = int(len(i))
print("the number you have entered is", num)
print("the length of the number you have entered is", len)

sum = 0
while (num!=0):
    val = num%10
    square = (val)** len
    sum = sum + square
    num = num // 10
    print("testing",sum)


if sum==b:
    print("the num is armstrong number")
else:
    print("the number is not armstrong number")


Another way to write this program:

Code:

print("Program to check a number is armstrong or not")
uinput="Y"
while(uinput=="Y"):
print("Enter a number")
num=input()
compare=int(num)
numi=int(num)
n=len(num)
sum=0
while(numi!=0):
mod=numi%10
sum=sum+mod**n
numi=numi//10

if sum==compare:
print("The number is armstrong")

else:
print("The no is not armstrong")

print("Do you want to check another number")
uinput=input()

Output:

Program to check a number is armstrong or not
Enter a number
153
The number is armstrong
Do you want to check another number
Y
Enter a number
153
The number is armstrong
Do you want to check another number
N

Coding screen

Output screen:

Leave a Reply

Your email address will not be published. Required fields are marked *