Saturday, 7 December 2024

Day 20 : Python Program to Find Sum of Digit of a Number using Recursion

 


def sum_of_digits(number):

    if number == 0:

        return 0

    return (number % 10) + sum_of_digits(number // 10)

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

result = sum_of_digits(abs(number))  

print(f"The sum of the digits of {number} is {result}.")


Code Explanation:

1. Function Definition

def sum_of_digits(number):

def: Declares a new function.
sum_of_digits: The name of the function, which computes the sum of the digits of a number.
number: Input parameter representing the number whose digits will be summed.

2. Base Case for Recursion

    if number == 0:
        return 0
if number == 0:: Checks if the number is 0.
This is the base case for recursion, ensuring the recursion eventually stops.
return 0: Returns 0 if the number is 0. This stops the recursive calls.
3. Recursive Case

    return (number % 10) + sum_of_digits(number // 10)
number % 10: Extracts the last digit of number.
+: Adds the last digit to the result of the recursive call.

4. Taking User Input

number = int(input("Enter a number: "))
input("Enter a number: "): Prompts the user to enter a number.
int(): Converts the input (string) into an integer.
number: Stores the user-provided number.

5. Handling Negative Input

result = sum_of_digits(abs(number))
abs(number): Converts the number to its absolute value (removes any negative sign).
This ensures the function works correctly for negative numbers.
result: Stores the result of the function call.
6. Displaying the Result

print(f"The sum of the digits of {number} is {result}.")
print(f"..."): Displays the sum of the digits in a user-friendly format using an f-string.
The original number and its sum are dynamically inserted into the string.

#source code --> clcoding.com 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (28) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (223) Cybersecurity (24) data management (11) Data Science (127) Data Strucures (8) Deep Learning (20) 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&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (4) PHP (20) Projects (29) Python (923) Python Coding Challenge (318) Python Quiz (4) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

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