Write a python program to get the sum of digits

1. Introduction

This blog post is dedicated to writing a Python program that calculates the sum of digits of a given number. This is a common task in programming, often used in various algorithmic challenges and applications. It's a great example to demonstrate basic arithmetic operations and looping in Python.

2. Program Steps

1. Accept or define a number.

2. Convert the number to a string to iterate over its digits.

3. Initialize a variable to keep the sum of digits.

4. Iterate over each digit, convert it back to an integer, and add it to the sum.

5. Return or print the sum of digits.

3. Code Program

def sum_of_digits(number):
    # Step 2: Convert the number to a string
    number_str = str(number)

    # Step 3: Initialize the sum variable
    sum = 0

    # Step 4: Iterate over each digit and add it to the sum
    for digit in number_str:
        sum += int(digit)

    # Step 5: Return the sum
    return sum

# Step 1: Define a number
num = 12345
result = sum_of_digits(num)
print(f"The sum of digits of {num} is {result}")

Output:

For the number 12345, the output will be 15, which is the sum of its digits (1 + 2 + 3 + 4 + 5).

Explanation:

1. The program starts with a number, num, and passes it to the sum_of_digits function.

2. Inside the function, the number is converted to a string (str(number)) so that we can iterate over each digit.

3. A sum variable is initialized to 0. It will store the cumulative sum of the digits.

4. The function then iterates over each digit in the string. Each digit is converted back to an integer (int(digit)) and added to the sum.

5. Finally, the sum of digits is returned and printed.

This method is an effective way to calculate the sum of digits of a number in Python, demonstrating the use of string manipulation, type conversion, and a for loop.


Comments