Armstrong Number in Python using For Loop

Armstrong Number in Python using For Loop | In this post, we will discuss the python program to find Armstrong numbers using a For Loop. Armstrong number is a number that when raised to the power of a number of its own digits is equal to the sum of that number.

For Example:-

(i) Let’s assume a number as 3, the number of digits is 1 so 3 to the power of 1 is 3 there 3 is an Armstrong number.

(ii) 371 – there are 3 digits so, each digit will be raised to 3
3*3*3 + 7*7*7 + 1*1*1 = 371. Therefore 371 is an Armstrong number.

Python Program to Find Armstrong Number using For Loop

We can also set intervals to find the Armstrong number; this works as follows. Python code takes two intervals, upper limit and lower limit, and checks for the Armstrong number in between them.

# Python program to find armstrong number using for loop

# take range
low = 1
up = 10

# find armstrong number in range
for i in range(low, up +1):
   pow = len(str(i))
   sum = 0
   temp = i
   while temp > 0:
      digits = temp %10
      sum += digits ** pow
      temp //= 10
   if i == sum:
      print(i)

Output:

1
2
3
4
5
6
7
8
9

In the code, we have taken an interval from 1 to 10 so the output will be the Armstrong number between 1 to 10, We use a for loop to iterate the number between the range and then find the Armstrong number between the specified range.

Armstrong Number in Python using For Loop

In the previous program, the range is hardcoded in the program but in this program, we will find the Armstrong number in an interval given by the user.

# Python program to find armstrong number using for loop

# take range
low = int(input("Enter the lower limit: "))
up = int(input("Enter the upper limit: "))

# find armstrong number in range
for i in range(low, up +1):
   pow = len(str(i))
   sum = 0
   temp = i
   while temp > 0:
      digits = temp %10
      sum += digits ** pow
      temp //= 10
   if i == sum:
      print(i)

Output for the input values test-case-1:-

Enter the lower limit: 1
Enter the upper limit: 300
1
2
3
4
5
6
7
8
9
153

In the example given we have set the lower limit as low to 1 and the upper limit as up to 300 then by using a for loop we find the Armstrong number between 1 and 300 and print the same.

Output for the input values test-case-2:-

Enter the lower limit: 1
Enter the upper limit: 750
1
2
3
4
5
6
7
8
9
153
370
371
407

In the example given we have set the lower limit as low to 1 and the upper limit as up to 750 then by using a for loop we find the Armstrong number between 1 and 750 and print the same.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *