Stuck on digit_sum


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096

In the console window, I get the following:

1
2
3
4
none

and an error message that says the following:

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

What I expected to happen is that my code would first convert the integer to a string and then iterate through that string, converting each element back into an integer and adding it to the variable total.


def digit_sum(n):
    n = str(n)
    total = 0
    for x in n:
        total = total + int(x)
        print x
        
digit_sum(1234)


#2

Do not print inside your function. Have it return the total once the loop is finished.


#3

Actually, I just realized it should be:

print total

Except that what that gets me is the following when printing inside the loop:

1
3
6
10
none

If I print outside the loop, I get:

10
none

10 is the right answer, but in BOTH cases above, I still get an error from codeacademy saying:

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

So I think I still have a logical error here.


#4

We are not instructed to print, only to return. The function must send something back to the caller else the caller sees None.


#5

Okay, I got it to work using the following code:

def digit_sum(n):
n = str(n)
total = 0
for x in n:
total = total + int(x)
return total

a = digit_sum(1234)
print a

The variable a printed 10 and the codeacademy app was happy, so moving on.

Thanks for the help.


#6

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