Sometimes, we want to sum the digits of a number with Python.
In this article, we’ll look at how to sum the digits of a number with Python.
How to sum the digits of a number with Python?
To sum the digits of a number with Python, we can create our own function.
For instance, we write
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
to create the sum_digits
function that has a while loop that runs when n
isn’t 0.
In it, we get the remainder of n
with divided by 10 with n % 10
.
Then we add the remainder to s
.
Next, we divide n
by 10 and round the quotient to the nearest integer.
And then we return the sum s
.
Conclusion
To sum the digits of a number with Python, we can create our own function.