Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python program to check whether the 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.
Here is an example of a Python program that checks if a given number is an Armstrong number:
Code For python program to check whether the given number is an Armstrong number
def is_armstrong(num): n = len(str(num)) temp = num sum = 0 while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 return sum == num n = int(input("Enter a number: ")) if is_armstrong(n): print(n,"is an Armstrong number") else: print(n,"is not an Armstrong number")
Enter a number: 371
371 is an Armstrong number
In this program, the
is_armstrong(num) function takes one argument: a number. The function first converts the number to a string and find the length of the string, This gives us the number of digits in the number.
Then it uses a
while loop to repeatedly extract the last digit of the number, raise it to the power of number of digits and add it to a sum. At the end of the loop, it compares the sum with the original number passed and returns True if the two are equal else False.
The program starts by asking the user to enter the number. This value is stored in the variable
n. The function is_armstrong is called with n as an argument. Based on the returned value of the function it prints whether the given number is an Armstrong number or not.
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.