4/15 Codecademy says it's wrong, visualizer says it's ok


#1

Hi, here is my code:

s =[]
def digit_sum(n):
    if n >= 0:
        n = str(n)
        for i in n:
            i = int(i)
            s.append(i)
        return sum(s)

Codecademy says 'your function fails on digit_sum(1000). It returns 12 when it should return 1.'
But when I launch it in visualizer like this:

s =[]
def digit_sum(n):
    if n >= 0:
        n = str(n)
        for i in n:
            i = int(i)
            s.append(i)
        print sum(s)
digit_sum(1000)

It prints '1'. What's wrong?


#2

Hi @szkaplerny ,

Your two functions are different. The first one uses return, but the second one only uses print. The function should return a value.

There are two problems with the first version of your function. This statement precedes the function definition, and should be moved so that it becomes the first statement inside the function ...

s =[]

That is so that it executes every time the function is called.

This statement is indented by two levels, so it is part of the if block ...

return sum(s)

Remove one level of indentation, so that it executes even when n is equal to 0.


#3

About your first paragraph:
Yea, I used print, but switched to return and then it returns 1 too (in visualiser). Why there are different results?
Here comes my next question - I added return before print, and program returns '1', but doesn't print it. Why? Or return or print? Of course I understand I should swap these two functions, but I'm just looking what will happen.

About your second reproof - I used n >= 0, so it would return even when n is equal 0, but I understand what you meant and I swapped it as you said.

At the end - I know I could write this program in better way, but what is your overall opinion about this one?


#4

its right just copy paste this:
def digit_sum(n):
sum = 0

for i in str(n):



    sum+=int(i)

return sum

digit_sum(434)