Python

# Number of Armstrong in Python2 min read

A positive number is called an Armstrong number if it is equal to the sum of the cubes of its numbers, for example 0, 1, 153, 370, 371, 407, etc.

In other words, the following equation will be verified

xy..z = xn + yn + ….. + zn

n is the number of digits

For example, 370 is a 3-digit Armstrong number

370 = 33 + 73 + 03
= 27 + 343 + 0
= 370

Now, let’s see the implementation of Armstrong’s number in Python.

Program to check if the given number is an Armstrong number

Output:

Here’s a line-by-line explanation of the code:

1. `num = int(input("Enter a number: "))`: This line takes input from the user as an integer and stores it in the variable `num`.
2. `sum = 0`: This line initializes the `sum` variable with 0, which will be used to store the sum of the cubes of each digit.
3. `temp = num`: This line creates a copy of the `num` variable and stores it in `temp`.
4. `while temp > 0:`: This line starts a while loop that continues until `temp` is greater than 0.
5. `digit = temp % 10`: This line finds the last digit of `temp` by using the modulo operator (`%`), and stores it in the `digit` variable.
6. `sum += digit ** 3`: This line adds the cube of `digit` to the `sum` variable.
7. `temp //= 10`: This line updates the `temp` variable by removing the last digit, by using integer division (`//`).
8. `if num == sum:`: This line checks if the `num` is equal to `sum`.
9. `print(num,"is an Armstrong number")`: If the condition in line 8 is true, this line prints the message indicating that `num` is an Armstrong number.
10. `print(num,"is not an Armstrong number")`: If the condition in line 8 is false, this line prints the message indicating that `num` is not an Armstrong number.