Wednesday, 4 December 2024

Day 12 : Python Program to Check Armstrong number

 


def armstrong(number):

    num_str = str(number)

    return number == sum(int(digit) ** len(num_str) for digit in num_str)


num = int(input("Enter a number: "))


if armstrong(num):

    print(f"{num} is an Armstrong number.")

else:

    print(f"{num} is not an Armstrong number.")

    

Explanation:

Function Definition


def armstrong(number):

     num_str = str(number)
  # Convert the number to a string to access individual digits.

    return number == sum(int(digit) ** len(num_str) for digit in num_str)

str(number):

 Converts the input number into a string so that you can iterate over its digits (e.g., 153 becomes "153").
len(num_str):
 Counts the number of digits in the number (e.g., for "153", the length is 3).
for digit in num_str: 
Iterates over each digit in the string representation of the number.

int(digit) ** len(num_str):

 Converts the digit back to an integer and raises it to the power of the number of digits.
sum(...): Sums up all the powered values for the digits.
number == ...: Compares the sum of powered digits with the original number to check if they are equal. The function returns True if they match, meaning the number is an Armstrong number.

Input

num = int(input("Enter a number: "))
Prompts the user to input a number, which is converted to an integer using int().

Check and Output

if armstrong(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")
if armstrong(num):: Calls the armstrong function to check if the number is an Armstrong number.

Depending on the result:

If True, prints: <number> is an Armstrong number.
If False, prints: <number> is not an Armstrong number.

#source code --> clcoding.com 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (76) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) Python (949) Python Coding Challenge (389) Python Quiz (45) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses