# Python – Check if Number is Armstrong

## Python Program to Check if Number is Armstrong

A number of n-digits is said to be Armstrong if it obeys the following condition.

``abcd... = pow(a,n) +  pow(b,n) + pow(c,n) + ...``

In this tutorial, we shall write a Python function, and also go through examples, where we shall check if a given number is an Armstrong number or not.

### Python Armstrong Function

Following is the Python function that takes a number and checks if the given number is Armstrong.

``````def armstrong(num):
num = str(num)
n = len(num)
result = 0
# compute pow(a,n)+pow(b,n)+...
for i in num:
result+=pow(int(i),n)
#no need to check if part of the expansion exceeds the given number
if(result>int(num)):
break
#check if given number equals expansion
if(int(num)==result):
return True
else:
return False``````
Run this program ONLINE

In the above function, we have defined following sequence of steps.

• Consider that the argument is string. If not, we are converting it to string using `str(num)`.
• `n = len(num)` finds the value of n, the number of digits in the given number.
• In the Python For Loop, we computed the sum of powers.
• In the Python If Else statement, we are checking if the argument is equal to the result of sum of powers equation. If the two numbers are equal, then the given number is Armstrong, else not.

### Example 1: Check if Given Number is Armstrong

In the following example, we will read a number from the user and check if that is an Armstrong Number.

Python Program

``````def armstrong(num):
num = str(num)
n = len(num)
result = 0
# compute pow(a,n)+pow(b,n)+...
for i in num:
result+=pow(int(i),n)
#no need to check if part of the expansion exceeds the given number
if(result>int(num)):
break
#check if given number equals expansion
if(int(num)==result):
return True
else:
return False

#read the number as a string
num = input('Enter a number: ')
result = armstrong(num)
print('Is ',num,' an Armstrong Numebr? ',result,sep="")``````

Output

``````C:\python>python example.py
Enter a number: 123
Is 123 an Armstrong Numebr? False

C:\python>python example.py
Enter a number: 153
Is 153 an Armstrong Numebr? True

C:\python>python example.py
Enter a number: 1634
Is 1634 an Armstrong Numebr? True

C:\python>python example.py
Enter a number: 413
Is 413 an Armstrong Numebr? False``````

### Summary

In this tutorial of Python Examples, we learned how to check if a given number is an Armstrong number of not.