Python Tutorials

Python Programs

Python Check Armstrong Number


Python Check Armstrong Number

In this tutorial, we will learn how to check if a number is an Armstrong number in Python. We will cover the definition of an Armstrong number and implement a function to check if a given number is an Armstrong number.


What is an Armstrong Number

An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.


Syntax

The syntax to check if a number is an Armstrong number in Python is:

def is_armstrong(number):
    digits = [int(d) for d in str(number)]
    power = len(digits)
    total = sum(d ** power for d in digits)
    return total == number


Checking if a number is an Armstrong number

We can create a function to check if a given number is an Armstrong number by summing the digits each raised to the power of the number of digits.

For example,

  1. Define a function named is_armstrong that takes one parameter number.
  2. Convert the number to a string and then to a list of its digits.
  3. Determine the number of digits in the number.
  4. Compute the sum of each digit raised to the power of the number of digits.
  5. Return True if the computed sum equals the original number, otherwise return False.
  6. Call the function with a sample number and print the result.

Python Program

def is_armstrong(number):
    digits = [int(d) for d in str(number)]
    power = len(digits)
    total = sum(d ** power for d in digits)
    return total == number

# Check if 153 is an Armstrong number
result = is_armstrong(153)

# Print the result
if result:
    print("153 is an Armstrong number")
else:
    print("153 is not an Armstrong number")

Output

153 is an Armstrong number