Why does return indent return different result?


#1



Excercise 3.3
Lists and Functions : 13. Modifying each element in a list in a function


Why does the indent at "return" in example A return the intended result where as example B returns something else. How does the indent of return change the result?


#Example A

n = [3, 5, 7]
def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x
print double_list(n)

#Example B

n = [3, 5, 7]
def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
        return x
print double_list(n)


#2

In the second example, the return statement is executed within the first iteration of the loop.


#3

return statement terminates execution of the function.

In the first example return will be executed after the for loop.

In the second example return is inside the block of for loop and will be executed in the first iteration.


#4

Makes sense! Thank you!


#5

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