Check Armstrong Number in Python
Prove that 153 equals its powered-digit sum with Python. A beginner walkthrough derives the exponent from digit count and safely handles negative responses.
1# Program to check Armstrong number23num = int(input("Enter an integer: "))45digits = str(abs(num))6power = len(digits)78total = 09for d in digits:10 total += int(d) ** power1112if total == num:13 print(num, "is an Armstrong number")14else:15 print(num, "is not an Armstrong number")
Output
153 is an Armstrong number
1³ + 5³ + 3³ equals the original 153.
In this one
- Use digit count as an exponent
- Accumulate powered digits
- Compare a computed total with the original
How it works
- 1
Read num, then form digits from its absolute value.
- 2
Set power to len(digits) and add int(d) ** power for each digit.
- 3
Compare total to num and print the result.
Edge cases
Single digit
Enter 7.
The exponent is one and the sum is 7, so it qualifies.
Negative input
Enter -153.
The digit sum is positive and cannot equal the signed original, so it is rejected.
What's going on
153 equals 1 cubed plus 5 cubed plus 3 cubed: 1 + 125 + 27. An Armstrong number uses the number of digits as the exponent, so this code is not limited to three-digit examples.
digits stores the text of the absolute value. Iterating it yields one digit string at a time; int(d) converts that digit before ** raises it to power. total collects the contributions, and the final comparison uses the original signed num.
Negative inputs cannot equal this non-negative sum, so they print not an Armstrong number without trying to convert a minus sign. Zero qualifies because its one digit contributes zero. Every non-negative single digit qualifies too: raising it to power one leaves it unchanged.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What exponent is used for 9474?
Pick an answer to check it.
Question 2
Why convert d with int?
Pick an answer to check it.
Questions people ask
What exponent is used for 9474?
Four, because the exponent is the number of decimal digits.
Why convert d with int?
Iteration yields digit strings, while exponentiation needs numeric operands.
Is zero an Armstrong number here?
Yes. Its single digit raised to power one contributes zero.