def armstrong(number):
num_str = str(number)
return number == sum(int(digit) ** len(num_str) for digit in num_str)
num = int(input("Enter a number: "))
if armstrong(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Explanation:
Function Definition
def armstrong(number):
num_str = str(number)
# Convert the number to a string to access individual digits.
return number == sum(int(digit) ** len(num_str) for digit in num_str)
str(number):
Converts the input number into a string so that you can iterate over its digits (e.g., 153 becomes "153").
len(num_str):
Counts the number of digits in the number (e.g., for "153", the length is 3).
for digit in num_str:
Iterates over each digit in the string representation of the number.
int(digit) ** len(num_str):
Converts the digit back to an integer and raises it to the power of the number of digits.
sum(...): Sums up all the powered values for the digits.
number == ...: Compares the sum of powered digits with the original number to check if they are equal. The function returns True if they match, meaning the number is an Armstrong number.
Input
num = int(input("Enter a number: "))
Prompts the user to input a number, which is converted to an integer using int().
Check and Output
if armstrong(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
if armstrong(num):: Calls the armstrong function to check if the number is an Armstrong number.
Depending on the result:
If True, prints: <number> is an Armstrong number.
If False, prints: <number> is not an Armstrong number.
#source code --> clcoding.com
0 Comments:
Post a Comment