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