Editor

Python Program to Check an Armstrong Number

Beginner · Numbers · CBSE class 11 practical list

An Armstrong number is a number equal to the sum of its digits, each raised to the power of the number of digits. For example, 153 has three digits and 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. This program splits a number into its digits and checks that rule.

Program

armstrong_number.py
num = 153 # or: num = int(input("Enter a number: "))
power = len(str(num)) # how many digits num has
total = 0
temp = num # work on a copy so num stays unchanged
while temp > 0:
digit = temp % 10 # the last digit
total += digit ** power
temp //= 10 # drop the last digit
print("Sum of the digits raised to the power", power, "is", total)
if total == num:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Output
Sum of the digits raised to the power 3 is 153
153 is an Armstrong number

How it works

  1. len(str(num)) counts the digits, which is the power each digit is raised to.
  2. temp % 10 gives the last digit, and temp //= 10 removes it, so the loop visits every digit from right to left.
  3. Each digit raised to that power is added to total.
  4. The loop works on a copy, temp, so the original num is still there for the final comparison.
  5. For three-digit numbers the power is 3, which is the "sum of cubes of the digits" rule many textbooks use.

Another way to write it

Find all Armstrong numbers below 10000

Find all Armstrong numbers below 10000
print("Armstrong numbers below 10000:")
for n in range(1, 10000):
digits = str(n)
power = len(digits)
total = 0
for d in digits:
total += int(d) ** power
if total == n:
print(n, end=" ")
print()
Output
Armstrong numbers below 10000:
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474

Looping over str(n) gives the digits as characters, and int(d) turns each one back into a number.

Try it yourself

Try num = 9474, a four-digit Armstrong number, and then num = 154, which is not one.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises