An Armstrong number (also called a narcissistic number) is a nonnegative integer equal to the sum of each digit raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³ and 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubn = 153
digits = str(n)
total = sum(int(d) ** len(digits) for d in digits)
print("Sum of powered digits:", total)
print("Armstrong number:", total == n)
Output:
Sum of powered digits: 153
Armstrong number: True
This general expression works for numbers with any number of decimal digits.
For a three-digit input, the exponent is 3. The original example is retained with a clearer result and input validation.
raw = input("Enter a three-digit number: ").strip()
if not (raw.isdecimal() and len(raw) == 3):
print("Enter exactly three digits")
else:
n = int(raw)
total = sum(int(d) ** 3 for d in raw)
print("Sum of cubes:", total)
print("Armstrong:", total == n)
Output:
Sum of cubes: 153
Armstrong: True
Use len() to choose the exponent dynamically.
def is_armstrong(n):
if n < 0:
return False
digits = str(n)
return n == sum(int(d) ** len(digits) for d in digits)
for n in (0, 1, 153, 371, 1634, 9474, 100):
print(n, is_armstrong(n))
Output:
0 True
1 True
153 True
371 True
1634 True
9474 True
100 False
This keeps the original page’s range-search concept, including its expected four-digit matches.
def is_armstrong(n):
digits = str(n)
return n == sum(int(d) ** len(digits) for d in digits)
print([n for n in range(10, 10000) if is_armstrong(n)])
Output:
[153, 370, 371, 407, 1634, 8208, 9474]
The fourth powers of 1, 6, 3 and 4 sum to 1634.
n = 1634
parts = [int(d) ** 4 for d in str(n)]
print(parts)
print(sum(parts))
Output:
[1, 1296, 81, 256]
1634
User input needs validation; a negative sign is not a digit.
raw = "-153"
if not raw.isdecimal():
print("Enter a nonnegative whole number")
else:
n = int(raw)
print(n)
Output:
Enter a nonnegative whole number
A fixed exponent of three is not the definition of a general Armstrong number.
n = 1634
cubes = sum(int(d) ** 3 for d in str(n))
powers = sum(int(d) ** len(str(n)) for d in str(n))
print(cubes, powers)
Output:
308 1634
input() returns a string. Convert and validate the value before doing arithmetic.Check 153, 370, 371, 407, 1634 and 9474. Explain each exponent. Use the companion practice notebook for runnable examples and self-checks.
Yes. 1³ + 5³ + 3³ = 153.
Yes, using fourth powers.
No. Use the number of digits as the exponent.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.