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
1 Like

u made it 100 times complex then i thought it can be, thanks for the comparison, altho all those operations u made were the only way? (the long code u made) or is the a simpler yet more advance way ?


Two basic rules of thumb are, simplicity/brevity and correctness/reliability. Any method that meets these two criteria is well on the way to being a viable approach. At this stage of learning we are more interested in arriving at many possible solutions, not just the best one.


ohh i see, and in the message i wrote the = there*
and thanks for your advice

1 Like