To sum the digits of a number in Python, you can use a loop which will get each digit and add them together.
def sumDigits(num):
sum = 0
for x in str(num):
sum = sum + int(x)
return sum
print(sumDigits(100))
print(sumDigits(213))
#Output:
1
6
When working with numbers in Python, the ability to easily get information and statistics from them is valuable.
For example, one interesting case is if you want to get the sum of the digits of a number.
We can easily get the sum of the digits of a number in Python by first splitting a number into its digits and then summing up the digits using a loop.
To get the digits of a number, we first convert the number to a string and loop over that string. Then for each digit, we add it to a running total.
Below is a simple example in Python of how you can add up all of the digits of a number using a loop.
def sumDigits(num):
sum = 0
for x in str(num):
sum = sum + int(x)
return sum
print(sumDigits(100))
print(sumDigits(213))
#Output:
1
6
Hopefully this article has been useful for you to learn how to sum the digits of a number in Python.