digit_sum


#1

THE CODE WORKS, BUT I HAVE THIS ERROR MESSAGE


#2

instead of printing the sum (soma) return it !!
return soma


#3

Can you solve it on the first way they ehplained,please?
I don't know how to divide a string :frowning2:


#4

By the time you reach that excercise you should be able or at least have an idea on how to divide strings. :relaxed:


#6

sorry fot late reply , you can use for loop , to loop for each character in string

str_name="this a string"
for n in str_name:
    print n

the output will be
t
h
i

a

s
t
r
i
n
g


#7

Thank you .I was obviously tired :upside_down:


#8

Please compare your code to mine below which I tested to be working fine

def digit_sum_2(n):
    
    #initialize digitsum to zero. We will use this to store the digit sum total
    digitsum = 0
    
    #to get lenght of number we need to convert it to the str using str() function
    for i in range(len(str(n))):    
        
        #Use modulo to get the rightmost digit of a number
        rightmost = n % 10
        #print "rightmost digit is ", rightmost
        #print "Original n is ",n
        
        #Add the number to the total
        digitsum += rightmost
        
        #Using floor divide to remove the rightmost digit
        n = n // 10
        #print "After removal n is ",n
        
    return digitsum
    
num = 1234
print digit_sum_2(num)

#9

just like mine
def digit_sum(n):
digitsum = 0
for s in range(len(str(n))):
rightmost = n % 10
digitsum += rightmost
n = n // 10
return digitsum


#10

def digit_sum(n):
    count=0
    for num in str(n):
        count=count+int(num)
    return count    :wink:

#11

Try this :


#12

I understand that codecademy wants what it wants and generally there is one response that it is looking for in particular but I would still like to know why this doesn't work. I have tried with and without the input being given. This works in console and in the lil window but I still get error returned wrong value

x = []
n = int(raw_input("what number: "))
def digit_sum(n):
while n > 0:
y = n % 10
x.append(y)
n /= 10
#print y
#print x
#print n
print sum(x)
return sum(x)
digit_sum(n)


#13

Ok so I moved the x = [] inside the function above the while loop and now I pass. I should really take the instructions far more literal. They did ask for a function as in single function not a function and a list.