Categories
Python Answers

How to sum the digits of a number with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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