Python Practice › Basic Programs › Program 19
Check an Armstrong number
Write a Python program to check whether a number is an Armstrong number: the sum of its digits, each raised to the power of the number of digits, equals the number (153 = 1³ + 5³ + 3³).
Input
153, 370, 123, 9474
Output
153 True 370 True 123 False 9474 True
Approach
- Count the digits.
- Raise each digit to that power and add them up.
- Compare the sum with the original number.
Solution
def is_armstrong(n): digits = str(n) power = len(digits) total = sum(int(d) ** power for d in digits) return total == n for n in [153, 370, 123, 9474]: print(n, is_armstrong(n))Output
153 True 370 True 123 False 9474 True
Line by line
Line 2
Turning the number into a string makes it easy to loop over its digits.
Line 3
The power is the number of digits: 3 for 153, 4 for 9474.
Line 4
The generator expression converts each digit back to int, raises it to power and sum() adds them.
Line 5
The function returns True only when the sum equals the number.
Learn the concept
New to this topic? Read the lesson, then come back.