Python Program to Check Armstrong Number
mediumwhile loopPython
A number is an Armstrong number when the sum of its digits, each raised to the power of the number of digits, equals the number itself.
The question
Read a positive integer and print whether it is an Armstrong number: the sum of each digit raised to the power of the number of digits equals the number itself (153 = 1³ + 5³ + 3³).
The code
program.py
n = int(input())
k = len(str(n))
total = 0
temp = n
while temp > 0:
total += (temp % 10) ** k
temp //= 10
if total == n:
print(n, "is an Armstrong number")
else:
print(n, "is not an Armstrong number")Input
123
Output
123 is not an Armstrong number
How it works
- 1k = len(str(n)) counts the digits — 3 for 153, 4 for 1634.
- 2Work on a copy (temp) so n is still available for the final comparison.
- 3Add (temp % 10) ** k for every digit, removing digits with temp //= 10.
- 4Compare the total with n.
Common mistakes
- Always cubing (** 3) — it works for 153 but fails for 4-digit Armstrong numbers like 1634.
- Changing n itself in the loop, so the final comparison is against 0.
Now solve a similar question yourself
A new Python question every time, checked instantly.
