def number_sum(number):
total = 0
number = abs(number)
while number > 0:
total += number % 10
number //= 10
return total
number = int(input("Enter a number: "))
result = number_sum(number)
print(f"The sum of the digits of {number} is {result}.")
Code Explanation:
1. Function Definition
def number_sum(number):
def: Declares a new function.
number_sum: 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. Initializing the Total
total = 0
total: A variable to store the cumulative sum of the digits. It is initialized to 0.
3. Handling Negative Input
number = abs(number)
abs(number): Converts the number to its absolute value, removing any negative sign.
This ensures the program works for negative numbers by treating them as positive.
4. Iterative Summation
while number > 0:
while number > 0:: Starts a loop that runs as long as number is greater than 0.
This ensures all digits are processed.
4.1 Extracting the Last Digit
total += number % 10
number % 10: Extracts the last digit of number.
4.2 Removing the Last Digit
number //= 10
number //= 10: Removes the last digit of number using integer division.
5. Returning the Result
return total
return total: Returns the sum of the digits after the loop completes.
6. 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.
7. Calling the Function
result = number_sum(number)
number_sum(number): Calls the number_sum function with the user-provided number.
result: Stores the returned sum of the digits.
8. 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 (result) are dynamically inserted into the string.
#source code --> clcoding.com
0 Comments:
Post a Comment