Python programs · Numbers
Python program to check an Armstrong number
An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. For example 153 = 1³ + 5³ + 3³.
Approach
- Convert the number to text so each digit can be visited.
- Raise each digit to the power of the number of digits, and add them up.
- Compare the total with the original number.
The program
n = int(input()) digits = str(n) total = 0 for d in digits: total += int(d) ** len(digits) if total == n: print(n, "is an Armstrong number") else: print(n, "is not an Armstrong number")
Sample run
Input
153
Output
153 is an Armstrong number
How the code works
Converting to text with str() lets the loop visit each digit, and len(digits) gives the power. For 153 there are 3 digits, so the total is 1 + 125 + 27 = 153. Using len(digits) instead of a fixed 3 makes the program work for numbers of any length, such as 9474.
Try changing it
- Print all Armstrong numbers between 100 and 999.
- Write the test as a function that returns
TrueorFalse.
Common mistakes
- Using a fixed power of 3 for every number.
- Forgetting
int(d), so the program tries to raise text to a power.