Digit_sum: converting string to int help


Part 4 (digit_sum) of Excercise 15 (practice makes perfect)

I'm getting a "expected a character buffer object". I think it happens at line 7, temp = int(convert.index(place))

I change the input "n" into a string and store that in "convert". Then I make a "length" variable to store the length of the string. I create a "total" variable to store the final result. I create a "place" variable for the string's index.

Then I create a while loop that runs as long as "place" is less than "length". The "temp" variable should find the character in the string, "convert", at the index, "place", and change it into an integer (I think that's where I'm messing up). Then I add "temp" to "total" and increase "place" by one to move to the next index.

def digit_sum(n):
    convert = str(n)
    length = len(convert)
    total = 0
    place = 0
    while place < length:
        temp = int(convert.index(place))
        total += temp
        place += 1
        return total



You should check this thread: Digital_sum

Thank you! :slight_smile:


This is the one i used works perfectly :slight_smile:
def digit_sum(n):
for x in range(len(a)):
return sum


Thank you guys for giving examples of code that work. However, can you explain why mine doesn't work? Is it because I don't need to index the string?


this is simpler and straight forward
def digit_sum(n):
for i in str(n):
return k


convert.index(place) this part? it's not subsetting the convert str to give you the char_integer


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