Digit_sum


#1


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

I had hoped to return a neat solution to the digit_sum problem without going into too much unfamiliar coding which I would soon forget. I must be over-simplifying the problem and my solution is None.

I expect it will take some further understanding of global/local variables.

def digit_sum(n):
    total = 0
    [int(i) for i in str(n)]
    while i < len(str(n)):
        total += n[i]

#2

well, i understand what you are doing here:

[int(i) for i in str(n)]

but now your newly created list, won't be stored anywhere, which would be a bit of a shame, you might want to change this:

i = [int(i) for i in str(n)]

now, take a look at this code, it is yours, with a bunch of print statements:

def digit_sum(n):
    total = 0
    i = [int(i) for i in str(n)]
    print i, " has length ", len(i)
    print n, "has lenght: ", len(str(n))
    while i < len(str(n)):
        total += n[i]
    return total
print digit_sum(1234)

both i and n are four, so your while loop is not going to execute, which is a good thing, since neither the length of i or n is changing, you would have a infinity loop.


#4

That's helpful. I added an x=0 and x+=1 into the loop and it now works well.