How to Find the Sum of Numbers in Python

Reading Time: 4 Minutes
Publication date:

A common task for beginner programmers is to calculate the sum and product of the digits of a number. The number can be input from the keyboard or randomly generated. Here’s how the task is described:

Given a number, find the sum and product of its digits.

For example, the sum of the digits of the number 253 is 10 because 2 + 5 + 3 = 10. The product of the digits of the number 253 is 30 because 2 * 5 * 3 = 30.

The challenge here is that the number of digits is not known in advance. It could be a three-digit number, as in the example above, or an eight-digit number, or a single-digit number.

Generally, it is assumed that this task should be solved arithmetically and using a loop. That is, some arithmetic operations should be performed sequentially on the given number to extract all its digits, then sum and multiply them.

This involves using operations of integer division and finding the remainder. If a number is divided by 10, the last digit of the number will be “lost”. For example, 253 ÷ 10 = 25 (remainder 3). On the other hand, the lost digit is the remainder. After extracting this digit, we can add it to the sum of the digits and multiply it by the product of the digits.

Suppose n is the number itself, sum is the sum of its digits, and product is the product of the digits. The algorithm to find the sum and product of the digits can be described in words as follows:

  1. Assign zero to the variable sum.
  2. Assign one to the variable product (since multiplying by zero would result in zero).
  3. While the value of the variable n is greater than zero, repeat the following:
  • Find the remainder when n is divided by 10, i.e., extract the last digit of the number.
  • Add the extracted digit to the sum and multiply the digit by the product.
  • Perform integer division of n by 10 to discard the last digit.

In Python, the remainder is found using the percent sign (%), and integer division is done using double slashes (//).

Here is the Python code for this program:

n = int(input("Enter a number: "))
sum = 0
product = 1
while n > 0:
    digit = n % 10
    sum += digit
    product *= digit
    n //= 10
print("Sum:", sum)
print("Product:", product)

Example Execution:

Enter a number: 253
Sum: 10
Product: 30

The values of the variables can be shortened as follows:

while n > 0:
    digit = n % 10
    sum += digit
    product *= digit
    n //= 10

The above program is only suitable for finding the sum and product of the digits of natural numbers, i.e., integers greater than zero. If the original number can be any integer, negative numbers and zero should be considered.

If the number is negative, it does not affect the sum of its digits. In such a case, using the abs function in Python, which returns the absolute value of the argument, will suffice. It will convert the negative number to a positive one, and the loop while n > 0 will work as before.

If the number is equal to zero, then according to logic, the sum of its digits and their product should be zero. The loop will not work. Since the initial value of product is 1, you should add a condition to check if the given number is zero.

A program that processes all integers can start as follows:

n = abs(int(input("Enter a number: ")))
sum = 0
product = 1
if n == 0:
    product = 0

Note that the conditional operator if digit != 0: in Python can be shortened to if digit: because 0 is false. All other numbers are considered true.

The mathematical algorithm described above for finding the sum and product of the digits of a number can be called classical or universal. Similarly, you can solve the problem in all imperative languages, regardless of the richness of their toolkit. However, the tools of the programming language may allow you to solve a problem in another way, which is often simpler. For example, in Python, you can avoid converting the entered string to a number but instead extract individual characters from it, which are converted to integers of type int:

a = input("Enter a number: ")
sum = 0
product = 1
for digit in a:
    sum += int(digit)
    product *= int(digit)
print("Sum:", sum)
print("Product:", product)

If you add a check to the code to verify that the extracted string character is indeed a digit, the program will become more versatile. With it, you can calculate the sum and product of the digits of not only integers but also real numbers and any string from which digits are extracted.

n = input("Enter a string: ")
sum = 0
product = 1
for digit in n:
    if digit.isdigit():
        sum += int(digit)
        product *= int(digit)
print("Sum:", sum)
print("Product:", product)

Example Execution:

Enter a string: This3 number3is9low!
Sum: 15
Product: 81

The string method isdigit checks if the string contains only digits. In our case, the role of the string is played by a single character extracted in the current iteration of the loop.

With in-depth knowledge of Python, you can solve the problem in even more sophisticated ways:

import functools
n = input("Enter a number: ")
n = [int(digit) for digit in n if digit.isdigit()]
sum = sum(n)
product = functools.reduce(lambda x, y: x * y, n)
print("Sum:", sum)
print("Product:", product)

The expression [int(digit) for digit in n if digit.isdigit()] is a list comprehension. If the string “234” is entered, a list of numbers will be obtained: [2, 3, 4].

The built-in sum function returns the sum of the elements given to it as an argument.

The function functools.reduce takes two arguments – a lambda expression and, in this case, a list. Here, the variable x accumulates the product, and y takes the next value of the list.

5 / 5. 1

Share:

Leave a comment