Python program to find Armstrong numbers in a certain range I have written a Python program to check for Armstrong numbers in a certain range.

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.

Here is my code:

lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

   order = len(str(num))

   sum = 0

   temp = num
   while temp &gt; 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10

   if num == sum:
       print(num)


Here is an example output:

Enter lower range: 200
Enter upper range: 5000

370
371
407
1634


So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.
Names

Using sum as a variable name is not adviced as it hides the sum builtin. I'd suggest sum_pow as an alternative.

Also, temp does not convey much information. I'd use remaining even though I am not fully convinced.

Extracting digits from a number

You've used divisions and modulo to compute the different digits for a number. You can use divmod which is a pretty unknown builtin which returns the result for both operations in one go.

That would give:

   remaining = num
   while remaining:
       remaining, digit = divmod(remaining, 10)
       sum_pow += digit ** order


Also, a better alternative would be to avoid doing this ourselves: extracting the different digits is pretty much what str does for us. Also, we already call it anyway, we could make the most out of it and reuse the result.

   num_str = str(num)
   order = len(num_str)
   sum_pow = 0
   for digit in num_str:
       sum_pow += int(digit) ** order


More builtins

Disclaimer: next comment may be a bit overwhelming for a beginner. Don't worry, just take your time and read documentation online if need be.

We've already delegated most of the hard work to Python builtins but we can go further. The summing part could be handled by the sum builtin along with generator expressions.

for num in range(lower, upper + 1):
   num_str = str(num)
   order = len(num_str)
   sum_pow = sum(int(digit) ** order for digit in num_str)
   if num == sum_pow:
       print(num)


Going further

A few other things could be improved from an organisation point of view:


split the code in functions
use the if name == "main" check


Going even further, we could write unit tests for the logic.