4. digit_sum


#1

Hello, I'm doing "Practise Makes Perfect" and I'm currently in "4. digit_sum".

This is the code I have:

def digit_sum(n):
    if n > 0:
        n = str(n)
        numbers = []
        for i in range(len(n)):
            numbers.append(n[i])
        numbers = int(numbers)
        for i in range(len(numbers)):
            return sum(i)
    else:
        print "Your number must be bigger than zero."

and I'm getting the error

Oops, try again. Your function crashed on 434 as input because your function throws a "int() argument must be a string or a number, not 'list'" error.

I think the error is in the numbers = int(numbers) line but I don't really know how to fix it.
Any help would be appreciated.
Thanks


#2

yea, the problem is in the line you think, numbers is a list:

['4', '3', '4']

why not create a variable, set it to zero:

total = 0

then use a for .. in .. (with or without range, your choice) and add the numbers total? Inside the loop, don't forget to cast the numbers back to a integer


#3

def digit_sum(n):
    if n > 0:
        n = str(n)
        for i in range(len(n)):
            total = 0
            total += int(n[i])
            return total
    else:
        print "Your number must be bigger than zero."

Do you mean something like this? I get this error:

Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11.

#4

better, but you should declare total before the loop, otherwise total is set back to zero in every run of the loop

oh, and a function ends the moment a return keyword is reached. Which in your case happens in the first run of the loop, you might want to change the indention of the return so the whole loop can run


#5

I didn't think of the total being reset each run and I had forgotten the return thing too. Thanks! It's working now.