Python Practice › Loop Programs › Program 35
Armstrong number with a loop
Write a Python program to check whether a number is an Armstrong number (153 = 1³ + 5³ + 3³) using a loop.
Input
153, 154
Output
153 is an Armstrong number 154 is not an Armstrong number
Approach
- Count the digits, then add each digit raised to that power.
Solution
for n in [153, 154]: power = len(str(n)) total, temp = 0, n while temp > 0: total += (temp % 10) ** power temp //= 10 print(n, "is an Armstrong number" if total == n else "is not an Armstrong number")Output
153 is an Armstrong number 154 is not an Armstrong number
Line by line
Line 2
The power equals the number of digits.
Lines 4-6
The loop peels off digits and adds their powers.
Learn the concept
New to this topic? Read the lesson, then come back.