# Digit sum help

#1

I'm getting correct output but still getting error message:

Your function fails on digit_sum(6). It returns 0 when it should return 6.

``````def digit_sum(n):  #n is a number input
counter = (len(str(n))-1)  #convrt 2 str, get(len - 1), used as counter and index
tempList = []  #variable = list... to contain extracted digit
for i in range(counter):
while counter != -1: # while NOT TRUE/FALSE will execute
n = str(n)  #convert int to string
digit = n[counter]  #using "counter" as index, "digit" to store value
tempList.append(int(digit))  #convert to int, append to list
counter -= 1
return sum(tempList) # sum(v), v needs to be int type
print digit_sum(12345)``````

#2

your code fails for single digits, because length - 1 is zero, so counter is zero, then your for loop never runs

#3

right. doesn't work in single digit.
thanks.

#4

any tips? do I need to scrap the whole code? I was trying to do it based on the first suggested hint... What did I do wrong?

#5

well, you could of course check if length is one, but not really nice

Your code is pretty lengthy, you could scrap it and start again. You can just loop over a string version of `n` and append to list, or declare a variable total and give it a value of zero and add all values to total (also using for loop)

#6

for i in range(counter)... he used "i" as index and use a variable set to 0 then add all values to variable to total(just as you suggested)

did not think the solution would be that simple.

thanks.

#7

you don't even have to use `range()`, you can just do `for i in str(n):` which gives you access directly to the values of the list

#8

hehe... feeling stupid right now. I spent a long time trying to come up with my code only to find a simple solution. It's a different way of thinking.

Paying my dues!

Thanks for the tip, I'll keep it in mind for next time.

#9

for i in str(n) did not work for me...

"string indices must be integers, not str"

#10

but then `i` contains the values from the list, no longer indexes, so you can add to total directly:

``total += int(i)``

#11

ok, got it.
using i in range() gives indexes...
using i on int() gives values...
I'll go try it out... thanks again.

#12

It worked.... Awesome!

#13

going thru the instructions again and it already says to use str() and int()... so dumb!

#14