Function to Calculate Sum of Digits in Python

In this exercise, you will develop a Python program with a function named "sum_digits" that takes a number as input and returns the sum of its digits. This exercise is perfect for practicing function definition, loops, and arithmetic operations in Python. By implementing this function, you will gain hands-on experience in handling function definitions, loops, and arithmetic operations in Python. This exercise not only reinforces your understanding of functions but also helps you develop efficient coding practices for managing user interactions.



Group

Mastering Functions in Python

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

 Copy 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

More Python Programming Exercises of Mastering Functions in Python

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.