Digit_sum help


#1



digit_sum


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

For integer 1234, returns 10, still says the above error


My code looks correct and does what I expect, however it still returns an error message. I have tested this for a bunch of other integers and the sums of the digits are correct, but still errors.


def digit_sum(n):
    string = str(n)
    lst = []
    for number in string:
        lst.append(number) 
        
    count = 0
    for i in lst:
        count += int(i)
        print count
        
digit_sum(1234)


#2

hi @jci55
Lots of extra code there, we can make it simple. :slight_smile:

with respect to your code, Youre not returning the count.

If we dont return anything,function by default returns None.

Use return keyword to do this.
makes sure indentation is correct!


#3

I keep forgetting the nuances between return and print. Thanks! how else could I make the code simpler?


#4

One of thing we can do right now is to reduce it to one loop and can also get rid of extra variables.


#5

I feel that using the method of % and floor (//) it is more convenient


#6

always use return in a function instead of printing the answer out in the function,

def digit_sum(n):
    n = str(n)
    sum = 0
    for i in range(len(n)):
        print n[i]
        sum += int(n[i])
    return sum
    
print digit_sum(raw_input("Please input an integer: "))

#7

Hello,

I am also struggling with this exercise and would be grateful for some help. My code looks like this:

def digit_sum(n):
    a = str(n)
    lst = [] 
    
    for number in a:
        lst.append(number)
        c = int(lst)
        print sum(c)

#8

Inside the body of for loop we need to make few changes.

1.First we will append number after casting them into int type.
2.After append is done, we just return the sum(lst) , Make sure indentation is done correctly.


#9

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