Python: Check Armstrong Number

1. Introduction

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For instance, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. In this post, we'll explore how to determine if a given number is an Armstrong number using Python.

2. Program Overview

1. Create a function to calculate the sum of digits raised to their respective count.

2. Take user input for the number to check.

3. Check if the number is equal to the value returned by the function.

4. Display the result.

3. Code Program

# Python program to check if a number is an Armstrong number

def is_armstrong(num):
    """Function to check if a number is an Armstrong number."""
    # Convert number to string to find its length (i.e., number of digits)
    num_str = str(num)
    power = len(num_str)
    # Calculate the sum of digits raised to the power of their count
    total = sum(int(digit) ** power for digit in num_str)
    return num == total

# Taking user input
num = int(input("Enter a number: "))

# Check if the number is an Armstrong number and display the result
if is_armstrong(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

Output:

(For an input of 153)
Enter a number: 153
153 is an Armstrong number.

(For an input of 123)
Enter a number: 123
123 is not an Armstrong number.

4. Step By Step Explanation

1. We begin by defining a function is_armstrong which takes a single integer argument num.

2. Inside the function, we convert the number to its string representation to easily determine its number of digits.

3. The variable power is set to the length of this string, which represents the number of digits.

4. Using a generator expression, we iterate through each digit, raise it to the power of the digit count, and sum these values. The sum is stored in the variable total.

5. The function returns True if num is equal to total, otherwise it returns False.

6. After defining the function, we prompt the user to input a number.

7. We then call our is_armstrong function with this number and display the appropriate message based on the result.

8. The outputs provided show the results for the numbers 153 and 123.

Comments