PythonMastery

Armstrong number program in Python

Check whether a number is an Armstrong number, like 153 = 1³ + 5³ + 3³, and find every Armstrong number below 1000.

An Armstrong number is equal to the sum of its own digits, each raised to the power of the number of digits. 153 has 3 digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153, so 153 is an Armstrong number.

The program

python
def is_armstrong(n):
    digits = str(n)
    power = len(digits)
    total = sum(int(d) ** power for d in digits)
    return total == n


n = int(input("Enter a number: "))

if is_armstrong(n):
    print(f"{n} is an Armstrong number")
else:
    print(f"{n} is not an Armstrong number")

Typed in this example: 153. Press Run to type your own.

output
Enter a number: 153
153 is an Armstrong number

How it works

Finding all of them below 1000

python
def is_armstrong(n):
    digits = str(n)
    power = len(digits)
    return sum(int(d) ** power for d in digits) == n


found = [n for n in range(1, 1000) if is_armstrong(n)]
print(*found)
output
1 2 3 4 5 6 7 8 9 153 370 371 407

Every one-digit number is an Armstrong number, because a single digit to the power 1 is itself. There are no two-digit ones, and only four with three digits. Change the range to range(1, 10000) to find the three four-digit ones.

Related programs: Strong number.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping