How return works in for loop?


#1
def digit_sum(n):
    n = str(n)
    x=0
    for y in n:
        x += int(y)
        return x
print digit_sum(434)`indent preformatted text by 4 spaces`

this wont work,but after I deleted the indentation before return,it works,why?


#2

Just dry run it. Suppose n = "12345".

On first iteration:

  1. y = "1"
  2. x += int(y) => x += 1 => x = 1
  3. return x

That return statement causes the value x (= 1) to be returned from the function. But remember that return also causes exit from the function. So, any block (for loop, while loop, if-else) that was inside the function would also be terminated. Hence, on step 3 of first iteration, the return statement causes exit from the method consequently causing exit from the for loop inside the method.

Metaphorically, if you were roaming through all the rooms (statements/blocks) in your house (method) in some order, and suddenly you need to urgently leave (return from) the house, then all the rooms that you hadn't visited (as well as the one in which you were currently standing) would be terminated from the visit.

Removing the four spaces before the return statement causes the return statement to no longer be a part of the loop so it only causes the exit from the method when the loop has finished.

Hope it helps!