Reputation: 901
I am trying to add all the digits of a positive integer. When I test out the number 434, the result was 4, instead of 11.
Here is what I have, I don't understand why is my code not going through all the digits of the number. How to correct it?
def digit_sum(x):
n=0
if x>0:
#get the end digit of the number,add to n
n+=x%10
#remove the end digit of the number
x=x//10
return n
Upvotes: 0
Views: 610
Reputation: 698
Although this is not a function, it helped me:
digits = "12345678901234567890"
digit_sum = sum(map(int, digits))
print("The equation is: ", '+'.join(digits))
print("The sum is:", digit_sum)
(This prints:
The equation is: 1+2+3+4+5+6+7+8+9+0+1+2+3+4+5+6+7+8+9+0
The sum is: 90
)
Upvotes: 1
Reputation: 881563
Two main constructs of procedural programming are:
An if
statement is a selection statement. Since you want to add up all the digits in the number, your use of if
is inappropriate. In other words, using a selection statement will only give you the sum of the first digit you process (the final 4
in 434
).
Instead you should use an iteration statement like while
:
def digit_sum(number):
sumOfDigits = 0
while number > 0:
sumOfDigits += number % 10
number = number // 10
return sumOfDigits
You'll notice I've used more descriptive variable names. That's a good habit to get into because it self-documents your code.
You can also look into more Pythonic ways of doing this, such as:
def digit_sum(number):
return sum([int(digit) for digit in str(number)])
Whether that can be considered better is open for debate but it's a well-known way of writing Python succinctly.
Upvotes: 2
Reputation: 76887
Instead of the if
statement, use a while
statement:
def digit_sum(x):
n=0
while x>0:
#get the end digit of the number,add to n
n+=x%10
#remove the end digit of the number
x=x//10
return n
The if will evaluate only once and return value on n after one iteration, while runs the code in a loop till all digits are added to the sum.
This will give:
In [2]: digit_sum(10)
Out[2]: 1
In [3]: digit_sum(434)
Out[3]: 11
Alternatively, a one liner:
In [4]: digit_sum = lambda x: sum(map(int, str(x)))
In [5]: digit_sum(434)
Out[5]: 11
If instead of 11, you want to sum those digits again as well to get a single digit, just recurse:
In [6]: def digit_sum(x):
...: n=0
...: while x>0:
...: #get the end digit of the number,add to n
...: n+=x%10
...: #remove the end digit of the number
...: x=x//10
...: return n if n < 10 else digit_sum(n)
...:
In [7]: digit_sum(434)
Out[7]: 2
Upvotes: 1
Reputation: 1168
I would convert the number to a string, then parse and sum each digit:
def digit_sum(x):
numList = [int(d) for d in str(x)]
return sum(numList)
Upvotes: 0