# Digit_sum

#1

Hello everyone, need some help with my code:

``````import math
n=int(raw_input("enter the number: "))
a=[]
print digit_sum(n)

def digit_sum(n):
k=len(str(n))
print "length is ",k
for i in range(0,k):
m=n/(10**(k-1))
m=math.floor(m)
a.append(m)
num=n%(k-1)
n=num
k-=1
return sum(a)``````

and error is:

Traceback (most recent call last):
File "python", line 4, in
File "python", line 13, in digit_sum
ZeroDivisionError: integer division or modulo by zero

Digit_sum
#2

If k is 0, you end up dividing by 0, an impossibility.

I changed up some of your code, and came up with this workable solution:

``````n=int(raw_input("enter the number: "))

def digit_sum(n):
k=len(str(n))
total = 0
for i in range (0,k):
total+=int(str(n)[i])

print digit_sum(n)``````

We take the number in as you did, and store its length in the variable `k`. Then, things get a little different. Instead of using a list to contain each digit, then adding them up, we just simply add them to a total variable that is contained locally inside the function. Then, once all digits have been added, we return the variable, to find the desired result. Using string indices, we can take the desired position in our string, and convert that to an integer. Once it's an integer, it's simple enough to just add it to our total. Using the `i` variable defined in the for loop, we know which iteration the loop is on, and which string index to use. (Hence, `str(n)[i]`.) This method also eliminates the need to use the math library, and its functions.

As a side note, make sure to define functions before you call them. If you don't, you're asking for errors.

#3

#4

Awesome dude! I was trying to get [i] using (len-1) but it doesn't work with single digit input. Thanks so much for this.

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.