# Digit_sum: converting string to int help

#1

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

#2

Hi!

You should check this thread: Digital_sum

Thank you!

#3

This is the one i used works perfectly
def digit_sum(n):
a=str(n)
sum=0
for x in range(len(a)):
sum+=int(a[x])
return sum

#4

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?

#5

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

#6

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

#7

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