Write Python. Understand every error.

Open the editor

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

  1. Convert the number to text so each digit can be visited.
  2. Raise each digit to the power of the number of digits, and add them up.
  3. 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

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: