Editor

Python Program to Find Armstrong Numbers in a Range

Beginner · Numbers

An Armstrong number is equal to the sum of its digits, each raised to the power of the number of digits, like 153 = 1^3 + 5^3 + 3^3. This program checks every number in a range and prints the Armstrong numbers it finds.

Program

armstrong_numbers_in_range.py
start = 100 # or: start = int(input("Enter the start: "))
end = 999 # or: end = int(input("Enter the end: "))
print(f"Armstrong numbers between {start} and {end}:")
for num in range(start, end + 1):
power = len(str(num)) # how many digits num has
total = 0
temp = num # work on a copy so num stays unchanged
while temp > 0:
digit = temp % 10
total += digit ** power
temp //= 10
if total == num:
print(num)
Output
Armstrong numbers between 100 and 999:
153
370
371
407

How it works

  1. The for loop checks each number from start to end in turn.
  2. len(str(num)) counts the digits, which is the power each digit is raised to.
  3. The while loop takes the digits off one at a time with % 10 and // 10, adding each one raised to that power.
  4. If the total equals the number, it is an Armstrong number; between 100 and 999 there are exactly four: 153, 370, 371 and 407.

Another way to write it

Using a function and digit strings

Using a function and digit strings
def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d) ** power for d in digits)
found = [n for n in range(1, 10000) if is_armstrong(n)]
print("Armstrong numbers from 1 to 9999:")
print(found)
Output
Armstrong numbers from 1 to 9999:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]

Every one-digit number counts, since a digit to the power 1 is itself, and the four-digit Armstrong numbers are 1634, 8208 and 9474.

Try it yourself

Change the range to 10000 to 99999 to find the three five-digit Armstrong numbers.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises