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.
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.
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
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,
is_armstrong
that takes one parameter number
.True
if the computed sum equals the original number, otherwise return False
.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")
153 is an Armstrong number