Python check armstrong number using for loop
In this post, you will learn how to write program in Python to check whether a given number is Armstrong or not.
An Armstrong number (or narcissistic number) for a given number of digits is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Formula to check Armstrong number
A positive number of n digits is called an Armstrong number of order n.
abcde.... = an + bn + cn + dn + en +
For example, to check if 153 is an Armstrong number:
- The number of digits, n, is 3.
- Calculate 13 + 53 + 33.
- 13 = 1,53 = 125, 33 = 27.
- Sum these values: 1 + 125 + 27 = 153.
Here's how you can check if a number is an Armstrong number using a for loop in Python:
# Function to check if a number is an Armstrong number
def is_armstrong_number(num):
# Convert the number to a string to easily iterate over its digits
num_str = str(num)
num_digits = len(num_str)
sum_of_powers = 0
# Iterate over each digit
for digit in num_str:
sum_of_powers += int(digit) ** num_digits
# Check if the sum of the powers of its digits equals the original number
return sum_of_powers == num
# Example usage
num = 153
if is_armstrong_number(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Output of the above code:
When you run this code with num = 153, it will output:
153 is an Armstrong number.
Code Explanation:
- The function is_armstrong_number takes an integer num as input.
- It converts num to a string to easily iterate over its digits.
- It calculates the number of digits in num using len(num_str).
- It initializes sum_of_powers to 0.
- It uses a for loop to iterate over each digit in the string representation of num.
- For each digit, it raises the digit to the power of the number of digits and adds the result to sum_of_powers.
- Finally, it checks if sum_of_powers equals the original number num and returns the result.