Python Program to check if a number is an Armstrong or not

In this tutorial, we will discuss Python program to check if a number is an Armstrong or not.

Before going to the program first, let us understand what is an Armstrong Number.

Armstrong Number:

  • An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its digits raised to the power of the number of digits.
  • For example, 153 is an Armstrong number because 13+53+33=1531^3 + 5^3 + 3^3 = 153.

Related: Python Program for Fibonacci Series

Program code for checking if a number is an Armstrong or not in Python

# Armstrong Number Checker in Python
def is_armstrong(num):
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = sum([int(digit) ** num_digits for digit in num_str])
    return sum_of_powers == num

number = int(input("Enter a number: "))
if is_armstrong(number):
    print(f"{number} is an Armstrong number.")
else:
    print(f"{number} is not an Armstrong number.")

Explanation

  1. Function Definition: The is_armstrong function takes an integer num as input and returns True if the number is an Armstrong number, and False otherwise.
  2. Sum of Powers: The function calculates the sum of each digit raised to the power of the number of digits using a list comprehension.
  3. Main Program: The program prompts the user to enter a number and then checks if it is an Armstrong number using the is_armstrong function.

Output

Python Program to check if a number is an Armstrong or not

  • When you run the above program, it will prompt you to enter a number.
  • After entering the number, it will check whether the number is an Armstrong number or not and print the result.

Conclusion

  • In this tutorial, we learned how to check if a given number is an Armstrong number using a Python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
  • Practice this example to enhance your programming skills and understanding of Armstrong numbers.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *