Python Program to check armstrong number or not

In this simple python program, we need to check for an Armstrong number. It's a beginner-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is an Armstrong number?

In this basic python program, we need to know what is meant by an Armstrong number. Armstrong number is a number in which the sum of the power raised to total digits in the number of each digit will be equal to the number itself. To know more about Armstrong numbers we have an interesting blog on The basics of Armstrong numbers

3 digit Armstrong number

A 3 digit number will be an Armstrong number if the sum of cubes of each digit will be equal to the number itself.

For example, let us take number 153 and to check that number is an Armstrong number or not,

  • we need to take the cube of 1, 5, and 3
  • add those cubes together
  • and check the result is equal to 153 or not ?
  • If it's 153, it's Armstrong's number. Else not
  • Here 1+125+27 =153, so it is an Armstrong number.

How to implement a 3 digit Armstrong number check in python?

In this simple python program, We have to accept the user's number and initialize the sum and temp variables. Use a while loop in python until the number is greater than zero. Split the number into digits using mod(%) operator by 10 and calculate the sum of every digit's cube in the number. Finally, divide the number by 10 to remove one digit from the number. Then take the cube of that digit and sum the digit cube with others and so on. After the calculation check whether sumand number are same ? if yes display the number is Armstrong otherwise not. 

ALGORITHM

STEP 1: Accept the number from the user to check for Armstrong using the input function in the python programming language and convert that string to an integer using int().

STEP 2: Initialize the sum as zero and use a temp variable to save the number from the user.

STEP 3: Add a while loop for splitting the number from the user and calculating the sum of the cube of each digit and do steps 4,5,6

STEP 4: Take one digit from the number using the mod operator.

STEP 5: Calculate the sum as sum + cube of that digit.

STEP 6: Divide the number by 10 to remove that digit and continue the loop.

STEP 7: Use an if condition to check the number == sum, and if it is correct, print the number is an Armstrong else, not Armstrong using the print statement in python language.

Python Source Code

                                          number = int(input("Enter a number: "))  
sum = 0  
temp = number  
  
while temp > 0:  
   integer = temp % 10   
   sum += integer ** 3  
   temp //= 10  

if number == sum:  
   print(number,"is an Armstrong number")  
else:  
   print(number,"is not an Armstrong number")  
                                      

OUTPUT

Enter a number:  153

153 is an Armstrong number