Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Check if a number is an Armstrong number - Python Program

Example 1 :

# Program : Armstrong number num = int(input("Enter a number: ")) digits = list(str(num)) power = len(digits) total = sum(int(d) ** power for d in digits) if total == num: print(f"{num} is an Armstrong number.") else: print(f"{num} is not an Armstrong number.")

Output

 
OUTPUT  :
Enter a number: 153
153 is an Armstrong number.
 
 

Explanation

  • Armstrong number = sum of its own digits each raised to the power of number of digits.
  • Uses list comprehension to calculate sum.
  • Works for any number of digits.

Example 2 : Advanced Program

# Program : Armstrong number def is_armstrong(num): """ Checks if a given number is an Armstrong number. Args: num: An integer. Returns: True if the number is an Armstrong number, False otherwise. """ # Convert the number to a string to get the number of digits num_str = str(num) num_digits = len(num_str) armstrong_sum = 0 # Calculate the sum of each digit raised to the power of num_digits for digit_char in num_str: digit = int(digit_char) armstrong_sum += digit ** num_digits return armstrong_sum == num # Get input from the user number_to_check = int(input("Enter a number: ")) # Check if it's an Armstrong number and print the result if is_armstrong(number_to_check): print(f"{number_to_check} is an Armstrong number.") else: print(f"{number_to_check} is not an Armstrong number.")

Output

 
OUTPUT  1 :
Enter a number: 153
153 is an Armstrong number.
 
OUTPUT  2 :
Enter a number: 123
123 is not an Armstrong number.
 

Explanation

is_armstrong(num) function:

  • Takes an integer numas input.
  • Converts numto a string (num_str) to easily determine the number of digits (num_digits) using len().
  • Initializes armstrong_sumto 0.
  • Iterates through each character (digit_char) in num_str.
  • Converts each digit_charback to an integer (digit).
  • Calculates digitraised to the power of num_digits using the ** operator and adds it to armstrong_sum.
  • Returns Trueif armstrong_sum is equal to the original num, indicating it's an Armstrong number; otherwise, returns False.