return¶To review, here is what return does.
def f(n):
n = n * 2
return n + 5
if __name__ == '__main__':
print(f(50))
What is happenning here is that first, n gets assigned the value 50. Then, the computation happens inside the function f(). Finally, the value of f(50) becomes (2*50+5), i.e., 105. That's what gets printed.
return stops the execution of a function¶Here is a simple function that returns the first even number in the list L. For example, if L = [3, 5, 7, 1, 10, 3, 2, 8], we want to return 10.
def first_even(L):
for e in L:
if e % 2 == 0:
return e
if __name__ == '__main__' :
print(first_even([3, 5, 7, 1, 10, 3, 2, 8]))
Why is 10 returned, and not 2 or 8? Because once e becomes 10, we execute the statement return e, which returns 10, and no further computation is done in first_even().
What if we want the first two even numbers? What we can do is return a list that contains the first two even numbers.
def first_two_evens(L):
res = []
for e in L:
if e % 2 == 0:
res.append(e)
return res[:2] #just return [res[0], res[1]]
We can use return here, just to save some computation (but not alter the result.)
def first_two_evens_B(L):
res = []
for e in L:
if e % 2 == 0:
res.append(r)
if len(res) == 2:
return res #we built up res, no point going further
return res