Python

# Python Program to check Armstrong Number using Function3 min read

An Armstrong number (also known as a narcissistic number or a pluperfect digital invariant) is a number that is equal to the sum of its own digits raised to the power of the number of digits.

For example, the number 153 is an Armstrong number because:

1^3 + 5^3 + 3^3 = 153

Similarly, the number 371 is an Armstrong number because:

3^3 + 7^3 + 1^3 = 371

And the number 9474 is an Armstrong number because:

9^4 + 4^4 + 7^4 + 4^4 = 9474

So, in general, if a number `n` has `d` digits, it is an Armstrong number if the sum of each digit raised to the power `d` is equal to `n`.

Here’s a Python program that uses a function to check if a number is an Armstrong number or not:

Way 1:

Way 2:

Way 3:

Output:

Explanation line by line:

1. `def is_armstrong(num):`: This line defines a function named `is_armstrong` that takes a single argument `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. `return num == sum`: This line returns the result of the comparison between `num` and `sum`.
9. `num = int(input("Enter a number: "))`: This line takes input from the user as an integer and stores it in the variable `num`.
10. `if is_armstrong(num):`: This line calls the `is_armstrong` function and checks its return value.
11. `print(num, "is an Armstrong number")`: If the condition in line 10 is true, this line prints the message indicating that `num` is an Armstrong number.
12. `print(num, "is not an Armstrong number")`: If the condition in line 10 is false, this line prints the message indicating that `num` is not an Armstrong number.