Python Program to Check Armstrong Number

1. Introduction

In this tutorial, we will learn how to write a Python program to check if a number is an Armstrong number.

An Armstrong number is an n-digit number that is equal to the sum of its own digits each raised to the power of n. It's a concept often encountered in introductory programming courses and is an interesting case study for loop and condition operations in Python.

For example, 153 is an Armstrong number because it's 1^3 + 5^3 + 3^3, which equals 153.

2. Program Steps

1. Accept or define a number to be checked.

2. Calculate the number of digits in the number.

3. Sum the digits each raised to the power of the number of digits.

4. Compare the sum to the original number.

5. Return the result and print it.

3. Code Program

# Function to check if a number is an Armstrong number
def is_armstrong_number(number):
    # Convert the number to a string to ease extraction of digits
    str_num = str(number)
    # Calculate the number of digits (n)
    num_digits = len(str_num)
    # Calculate the sum of the digits raised to the power of n
    sum_of_digits = sum(int(digit) ** num_digits for digit in str_num)
    # Compare the sum to the original number
    return sum_of_digits == number

# Number to be checked
num_to_check = 153
# Check if the number is an Armstrong number and print the result
if is_armstrong_number(num_to_check):
    print(f"{num_to_check} is an Armstrong number.")
else:
    print(f"{num_to_check} is not an Armstrong number.")

Output:

153 is an Armstrong number.

Explanation:

1. is_armstrong_number is a function that determines whether a given number is an Armstrong number.

2. The number is converted to a string str_num to facilitate the extraction of individual digits.

3. num_digits, the number of digits in number, is computed using len(str_num).

4. A sum is calculated using a generator expression that raises each digit to the power of num_digits and adds them together.

5. The function checks if sum_of_digits is equal to number, returning True if they match, indicating it is an Armstrong number.

6. The function is tested with num_to_check set to 153.

7. If the condition is met, the print statement confirms that 153 is an Armstrong number, as the sum of the cubes of its digits is equal to the number itself.

Comments