Last Updated:

Sum and product of digits of a number in Python

Sum and product of digits of a number in Python

In order to find the sum or product of the digits in a number, you can use several algorithms. Let's look at them.

The first is to convert a number to a string and access each item by index using a for loop.

result = input()
sum = 0
mult = 1
for num in result :
sum += int(num)
much *= int(num)

But this option may have its drawbacks, so it is better to immediately move on to the next one. In python, it is possible to get the remainder of division, and if we divide the number by 10, then the remainder will be the last digit in the number.

 

From here we get the algorithm:

 

number = int(input())
plus = 0
while n > 0:
temp = number % 10
plus = plus + temp
number = number // 10

On the 5th line of the code, we get the last digit of the number, then we carry out various manipulations with it. And on the 8th line, we remove this very last digit from the number.

Sum() function in python

There are several ways to calculate the sum (and not only the sum) of all the numbers in an array. To begin with, let's try to write an algorithm using a loop, it will look like this:

def sum(list):
result = 0
for item in list:
result = result + item
return result
print(list([1,3,5,7,9]))

It is clear that the amount here can be replaced by anything.

It has been said more than once that Python loves its users and therefore there is already a built-in function called Sum(). It is needed to add up all the elements of the sequence.

print sum( [1,2,3] )
# 6

Only, unfortunately, there is no such function that could multiply the values or perform another action on them. But they are used extremely rarely, unlike this one.

Finally, I would like to remind you that the most important part in programming is practice. Therefore, try to write the algorithms written above yourself and it will be of great benefit. Success!