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³).
153, 370, 123, 9474
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))153 True 370 True 123 False 9474 True
Line by line
Turning the number into a string makes it easy to loop over its digits.
The power is the number of digits: 3 for 153, 4 for 9474.
The generator expression converts each digit back to int, raises it to power and sum() adds them.
The function returns True only when the sum equals the number.
Learn the concept
New to this topic? Read the lesson, then come back.