Issue
I am writing a simple program that will calculate the sum of the digits. So for example 123
would be 1 + 2 + 3 = 6
simple. When I write my code
def sumOfNumber(number):
sum = 0
while(number >= 1):
temp = number % 10
sum += temp
number /= 10
return sum
main():
sumOfNumber(123)
# 6.53
Can anyone explain this?
Solution
You seem to be using Python3 where division /
outputs floats. Replace the inplace division /=
with integer division //=
to get rid of decimals.
number //= 10
Although, if you want to manipulate a number digit by digit, it is better to cast it to a str
. This allows to loop over its digits and sum them.
def sumOfNumber(number):
digits = str(number)
sum_ = 0
for d in digits:
sum_ += int(d)
return sum_
sumOfNumber(123) # 6
Using the builtin sum
function, you can even rewrite this function in a single line.
def sumOfNumber(number):
return sum(int(x) for x in str(number))
Answered By - Olivier Melançon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.