How can I break down these problems into easier parts?


on the right hand side of the assign operator, there you can cast values to a specific type, which are then stored in the variable, simple example:

variable = int(value)


Thanks. So now I have:

def digit_sum(n):
  number = 0
  for number in str(n):
    number = int(number) + int(number)
    return number
print digit_sum(434)

But when running the code it returns 8 when it should return 11.


The iterator variable should not be the same name as the accumulator variable. Try using a different name.


Ignore this post. Ignore this post.


Okays, so I got it to add the first argument to itself (the following code prints 6 to terminal). How do I get it to add the numbers in the proper sequence?

def digit_sum(n):
  total = 0
  string = str(n)
  for number in string:
    total = int(number) + int(number)
    return total
print digit_sum(34)


If we look closely we can see where that comes from…

int(number) + int(number)

which is essentially, 2 * number. The indented return causes the function to exit on the first iteration…

int(3) + int(3) => 6

To correct the first issue,

total = total + int(number)

To correct the second issue, unindent so the return lines up with for.

for ...:
    # code
return total