Easy Tutorial
❮ Python Prime Number Intervals Ref Math Expm1 ❯

Armstrong Number in Python

Python3 Examples

An n-digit positive integer is called an Armstrong number if it equals the sum of its digits raised to the power of n. For example, 1^3 + 5^3 + 3^3 = 153.

Armstrong numbers within 1000:

1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

The following code checks whether the number entered by the user is an Armstrong number:

Example (Python 3.0+)

# Filename : test.py
# author by : www.tutorialpro.org

# Python checks if the user input is an Armstrong number

# Get user input
num = int(input("Please enter a number: "))

# Initialize sum
sum = 0
# Exponent
n = len(str(num))

# Check
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** n
   temp //= 10

# Output result
if num == sum:
   print(num, "is an Armstrong number")
else:
   print(num, "is not an Armstrong number")

Execution of the above code produces the following results:

$ python3 test.py 
Please enter a number: 345
345 is not an Armstrong number

$ python3 test.py 
Please enter a number: 153
153 is an Armstrong number

$ python3 test.py 
Please enter a number: 1634
1634 is an Armstrong number

Get Armstrong numbers within a specified range

Example (Python 3.0+)

# Filename : test.py
# author by : www.tutorialpro.org

# Get user input for range
lower = int(input("Minimum value: "))
upper = int(input("Maximum value: "))

for num in range(lower, upper + 1):
   # Initialize sum
   sum = 0
   # Exponent
   n = len(str(num))

   # Check
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** n
       temp //= 10

   if num == sum:
       print(num)

Execution of the above code produces the following results:

Minimum value: 1
Maximum value: 10000
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

The above example outputs Armstrong numbers between 1 and 10000.

Python3 Examples

❮ Python Prime Number Intervals Ref Math Expm1 ❯