Exercise
Function To Calculate Sum Of Digits
Objective
Develop a Python program with a function named "sum_digits" that takes a number as input and returns the sum of its digits. For instance, if the input number is 123, the function should return 6.
For example: print(sum_digits(123)) should output 6.
Example Python Exercise
Show Python Code
# Define the sum_digits function
def sum_digits(number):
total = 0
# Convert the number to a string to access each digit
for digit in str(abs(number)): # abs() to handle negative numbers
total += int(digit) # Add each digit to the total
return total
# Main function to test the sum_digits function
def main():
number = 123
print(sum_digits(number)) # This should print 6
# Call the main function to execute the program
if __name__ == "__main__":
main()
Output
6
Share this Python Exercise