The sum of digits of a number is the total sum of all its individual digits. For example, the sum of digits of 123 is:
\[ 1 + 2 + 3 = 6\]In this tutorial, we will write a Python program to calculate the sum of digits of a given number.
Python Program to Find the Sum of Digits
# Function to calculate sum of digits def sum_of_digits(num): total = 0 while num > 0: total += num % 10 # Extract the last digit and add to total num //= 10 # Remove the last digit return total # Taking user input number = int(input("Enter a number: ")) # Calculating and displaying the sum of digits result = sum_of_digits(abs(number)) # Using abs() to handle negative numbers print(f"Sum of digits of {number} is: {result}")
How It Works
- Extract the last digit using num % 10.
- Add it to the sum and remove the last digit using num //= 10.
- Repeat until all digits are processed.
- The result is the sum of all digits.
Output
Enter a number: 1234 Sum of digits of 1234 is: 10
Using Recursion
We can also solve this problem using recursion.
# Recursive function to find sum of digits def sum_of_digits_recursive(num): if num == 0: return 0 return (num % 10) + sum_of_digits_recursive(num // 10) # Taking user input number = int(input("Enter a number: ")) # Calculating and displaying the sum of digits result = sum_of_digits_recursive(abs(number)) print(f"Sum of digits of {number} is: {result}")