4/15 Digit_sum help

def digit_sum(n):
  result = 0
  str_position = len(str(n))
  str_value = str(n)
  #Missing code to identify x
  for x in str_position:
    result = result + int(x)
    str_position += 1  return result

print digit_sum(1234)

Hello all, phew this has been a very difficult chapter. I’ve been doing and redoing this section several times to make sure I understand it (and I plan to do it once more after I complete all of the tutorial as this is great practice). I’m stuck though.

My best guess with what is currently wrong is that there’s nothing to identify the variable “x”. That is to say there’s nothing tying it to the “n” variable. I wanted to do something along the lines of result = result + int(str(n)) but that didn’t work out.



str_position += 1  return result

you have two lines of code on a single line. That can’t be


for x in str_position:

str_position is a integer, you can’t loop over a integer. You seem to mix two things:

  1. a for loop which can loop over str_value directly, given you the numbers/values. Then you don’t need str_position.
  2. using a while loop in which you can use str_position, this gives you indexes which you then can use to retrieve value from string, convert to integer and add to result


Thanks! I had actually figured it out in the mean time. I had been doing too many of these in a row and just needed a break to realize my mistake.


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