12/18 personal experiment: return and print does not come out with the same value despite same list and function


m = [ 3, 5, 7, 9, 11, 13, 15 ]

def sample(x):
_for i in range(1, 4):
__return x[i]

print sample(m)

def second_sample(x):
_for i in range(1, 4):
__print x[i]


the first code returned with 5 while the latter code returned with 5, 7, 9. How come? both codes are identical in their function except for either return or print. anyone have any ideas? thank you

12/18 Created my own code apart from the needed one. Personal experiment

The reason why the first method with only give you 5 is because whenever we call return in a function we are done with the function what ever comes after is unreachable. So when you do

def sample(x):
    for i in range(1, 4):
        return x[i]

after the very first element is returned (i.e. x[1]) the for loop with terminates and so does the method hence we get 5 as the only result

On the other hand the print statement does not terminate anything hence it will execute till the for loop itself terminate that's why we get all the elements we wanted to print