Numbers · beginner
Python Program to Check Armstrong Number
Check whether a number is an Armstrong (narcissistic) number in Python by raising each digit to the number of digits, and find all of them below 10,000.
- str() and int()
- generator expressions
- sum()
- exponent operator **
An Armstrong number (also called a narcissistic number) equals the sum of its digits, each raised to the power of the number of digits. 153 has three digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153, so it is an Armstrong number.
The power depends on the length: for four-digit numbers such as 9474 every digit is raised to the fourth power. Some solutions always use cubes, which only works for three-digit numbers.
The program
def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d) ** power for d in digits)
for n in [153, 370, 9474, 123]:
print(n, "is an Armstrong number" if is_armstrong(n) else "is not an Armstrong number")
print([n for n in range(1, 10000) if is_armstrong(n)])153 is an Armstrong number
370 is an Armstrong number
9474 is an Armstrong number
123 is not an Armstrong number
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]How it works
- str(n) turns 153 into the text "153", which makes it easy to loop over the digits.
- len(digits) is the number of digits, used as the power.
- The generator expression turns each digit back into an int, raises it to that power, and sum() adds them up.
- The number is an Armstrong number when the sum equals the original number. Every single-digit number qualifies, because d¹ = d.
Watch it run line by line
Visualize is_armstrong(153) and look at the frame: digits is "153" (a string) and power is 3. The return row shows True once the sum has been compared.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Using arithmetic instead of strings
The digits can also be taken off with % 10 and // 10. This is how the problem is solved in languages without easy string conversion.
n = 9474
power = len(str(n))
total, rest = 0, n
while rest > 0:
total += (rest % 10) ** power
rest //= 10
print(total == n)TrueCommon mistakes
- Always using the cube (** 3), which wrongly rejects 9474 and other four-digit Armstrong numbers.
- Changing n itself in the while loop and then comparing the sum with the modified n (which is 0 by then). Work on a copy such as rest.
- Using / instead of // to drop the last digit: / gives a float, so the loop never reaches 0 cleanly.
Try it yourself
- Find the Armstrong numbers with five digits (there are three).
- Read a number with input() and print whether it is an Armstrong number.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.