Armstrong Numbers in Range in Python

Print all Armstrong numbers in a given range using loops.

BeginnerLoop ProgramsExample 18 of 25
armstrong-numbers-in-range.py
1# Program to print Armstrong numbers in a range
2
3start = int(input("Enter start of range: "))
4end = int(input("Enter end of range: "))
5
6for num in range(start, end + 1):
7 digits = str(num)
8 power = len(digits)
9 total = 0
10 for d in digits:
11 total += int(d) ** power
12 if total == num:
13 print(num)

Output

Enter start of range: 1
Enter end of range: 500
1
153
370
371
407

What's going on

We extend the Armstrong number logic to every number in the range and print those that satisfy the condition.

After this program

If the idea is still fuzzy, read Day 9: Loops and Iteration in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 loop programs, or see every topic on Python exercises.