Why does this code not work for the task digit_sum



My program doesn't work. I know where the error is but I don't know how I can fix it.


The error message I get is: "Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!"

Why is the length of the string out of range? Shouldn't it be the last letter of the string? If I change it to len - 1 in line 3 it does what it is supposed to do but starting with the second last digit. Thank you for your help in advance

def digit_sum(n):
    string = str(n)
    length = len(string) 
    su = 0
    while length > 0:
        su += int(string[length])
        length -= 1
    return su

a = 1234


The trouble is in the line:

su += int(string[length])

The length in this case is 4, so what that line is saying is:

su += int(string[4])

But the index of the string looks like this : 0, 1, 2, 3. There is no 4, so the string index string[4] is out of range.

To fix this use: su += int(string[length - 1])
You won't have to change the length in line 3.
Hope this helps.


You are overthinking this. Try following this template:

    VAR_1 = 0
        VAR_1 += int(INDIVIDUAL_ITEM)
    return VAR_1

As always, don't just follow the template and move on. Make sure you understand how and why it works. If you have any questions at all, please, just ask.


Thank you for your help. I have one more question though why does it not work when I change it inline 3 (so that it says len(string) - 1) isn't that the same as changing it in line 6?


Yeah, that is easier but as long as I can solve the task I'm happy :slight_smile:


Yes, but do you understand how and why it works? The point here is not to simply pass and move on, it is to understand what you are doing. How are you to learn coding if you don't know why your code does what it does or how it does it?


It is not the same.

Line 3 is setting the length of the string:
length = len(string)

The number 1234 has a length of 4.

Line 6 is setting the index number you want to start from, not the length itself:
int(string[length - 1])

1 2 3 4 is the position of each number
0 1 2 3 is the index, so position 1 is in index[0].

You want to start at the last position and count down, so you need to count down 4 times. You get this from the length.
But the last position is index[3] (or string[3] in your code). You get this from length - 1.

The 2 lines do 2 different things, so you need them both.


That's why I am fine with having a more complicated code than possible because I made it myself. That way I can understand it and since I did it myself I even came up with the idea how I could solve the problem. Yes, I do understand your code though if that's what you were asking :slight_smile:


Ok, thanks for clearing that up :slight_smile:


As long as it works and you understand it, it's a.o.k in my book.


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