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
str(n)gives the digits as text, andlen(digits)counts them. For 153,poweris 3.int(d) ** powerturns each digit back into a number and raises it to that power.sum(...)adds the results. If the total equals the original number, the function returnsTrue.- The function is meant for positive numbers. A minus sign is not a digit, so
int("-")would raise aValueErrorfor negative input.
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.