Python Program to Calculate the Sum of Digits

Introduction

Calculating the sum of the digits of a number is a common problem in programming. This tutorial will guide you through creating a Python program that takes a number as input and calculates the sum of its digits.

Example:

  • Input: 1234

  • Output: The sum of the digits is 10

  • Input: 567

  • Output: The sum of the digits is 18

Problem Statement

Create a Python program that:

  • Takes a number as input.
  • Calculates the sum of its digits.
  • Displays the result.

Solution Steps

  1. Take Input from the User: Use the input() function to get a number from the user.
  2. Convert Input to Integer: Convert the input string to an integer.
  3. Calculate the Sum of Digits: Iterate over each digit, convert it to an integer, and calculate the sum.
  4. Display the Result: Use the print() function to display the sum of the digits.

Python Program

# Python Program to Calculate the Sum of Digits
# Author: https://www.rameshfadatare.com/

# Step 1: Take input from the user
num = input("Enter a number: ")

# Step 2: Calculate the sum of digits
sum_of_digits = sum(int(digit) for digit in num if digit.isdigit())

# Step 3: Display the result
print(f"The sum of the digits is {sum_of_digits}")

Explanation

Step 1: Take Input from the User

  • The input() function prompts the user to enter a number. The input is treated as a string to handle each digit separately.

Step 2: Calculate the Sum of Digits

  • A generator expression is used within the sum() function to iterate over each character in the input string. Each character is checked to ensure it is a digit (isdigit()), then converted to an integer, and added to the sum.

Step 3: Display the Result

  • The print() function is used to display the calculated sum of the digits.

Output Example

Example 1:

Enter a number: 1234
The sum of the digits is 10

Example 2:

Enter a number: 567
The sum of the digits is 18

Example 3:

Enter a number: -9876
The sum of the digits is 30

Conclusion

This Python program demonstrates how to calculate the sum of the digits of a number by converting the number to a string and iterating over each character. This example is helpful for beginners to understand loops, string manipulation, and type conversion in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top