Python program that checks if a given number is an Armstrong number:
number = int(input("Enter a number: "))
# Initialize variables
original_number = number
result = 0
# Find the number of digits in the number
number_of_digits = len(str(number))
# Check if the number is Armstrong
while number > 0:
digit = number % 10
result += digit ** number_of_digits
number //= 10
if original_number == result:
print(original_number, "is an Armstrong number.")
else:
print(original_number, "is not an Armstrong number.")
The program prompts the user to enter a number using the input() function, and stores the value in the variable “number”. It then uses a while loop to check if the number is an Armstrong number. An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the number of digits in the number. It first finds the number of digits in the number by converting it into a string and finding its length, then it uses the while loop to iterate through each digit of the number, raise it to the power of the number of digits and add it to the variable “result”. At the end of the loop, it checks if the original number is equal to the result, if yes, the number is an Armstrong number, otherwise, it is not an Armstrong number.
You can also use the built-in python function pow()
to raise the digit to the power of the number of digits and list comprehension to generate the list of digits in the number,
number = int(input("Enter a number: "))
num_digits = len(str(number))
if number == sum([int(i) ** num_digits for i in str(number)]):
print(number,"is an Armstrong number.")
else:
print(number,"is not an Armstrong number.")
Both the methods will give you the same output which is whether the number is Armstrong or not. You can use any method that suits your need or preference.