digit_sum: Why doesn't my code work?


#1

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

Can anyone tell me why this returns the wrong sum? It returns a huge number instead of the right one.


def digit_sum(n):
    a = str(n)
    b = []
    for i in a:
        b.append(int(n))
        abc = sum(list(b))
    return abc


#2

Back this line out of the loop.


#3

Its still not working now I've done that.


#4

Turn b into an integer then add the a into it and convert the i variable back to an int while doing it as follows.

b = 0

b += int(i)

Then return the b for your grand total. Also mtf meant to say move the abc variable with its code back one indentation so it's no longer in the loop.


#5

I worked it out! I also needed to change the n in the (int(n)) into an i. Can't believe I didn't see that!