How to Write a Python Program to Check if a Given Number is an Armstrong Number?

Estimated read time 2 min read

To check if a given number is an Armstrong number, you can follow these steps to write a Python program:

  1. Get the input number from the user.
  2. Convert the input number to a string to iterate over its digits.
  3. Calculate the number of digits in the input number using the len() function.
  4. Initialize a variable armstrong_sum to 0. This variable will store the sum of the individual digits raised to the power of the number of digits.
  5. Iterate over each digit of the input number using a for loop.
  6. Convert each digit from string to an integer using the int() function.
  7. Raise each digit to the power of the number of digits and add the result to the armstrong_sum variable.
  8. After the loop, check if the armstrong_sum is equal to the original input number.
  9. If the armstrong_sum is equal to the input number, print that the number is an Armstrong number. Otherwise, print that it is not.

Here’s the complete code for the program:

# Step 1: Get input number from the user
num = int(input("Enter a number: "))

# Step 2: Convert the number to a string
num_str = str(num)

# Step 3: Calculate the number of digits
num_digits = len(num_str)

# Step 4: Initialize the armstrong sum
armstrong_sum = 0

# Step 5: Iterate over each digit
for digit in num_str:
    # Step 6: Convert digit from string to integer
    digit_int = int(digit)
    
    # Step 7: Calculate the sum of digits raised to the power of the number of digits
    armstrong_sum += digit_int ** num_digits

# Step 8: Check if the sum is equal to the original number
if armstrong_sum == num:
    print(num, "is an Armstrong number.")
else:
    print(num, "is not an Armstrong number.")

Now you can run the program, enter a number, and it will tell you whether the number is an Armstrong number or not.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply