2

I'm in the process of learning python, and I can't wrap my head around a piece of code in the book:

def find_value(List, value):

    for i in range(len(List)):
        if List[i] == value:
            return i

    return -1

I've tried running the code, and it returns the index if the value is in it, and returns -1 if it isn't, but what I don't understand is since the 'return -1' is outside the for loop, and if statement, should it not be run every time the code is executed? Or does return only get processed once, the first time it is called?

I just want to make sure I understand this concept before moving on. Thanks in advance

Yabusa
  • 579
  • 1
  • 6
  • 15

3 Answers3

5

No, you can have as many return statements in as many places as you like:

def function():
    ... # do something
    return 1
    return 
    return [3, 4, 5]
    return next(__import__('os').walk('.'))[-1:-1000000000:-1]

Though the important thing to keep in mind that only the first return that your function encounters will count, and anything else that would've succeeded it is not touched.

In the function above, you'll get 1 as the result and nothing else.

This sort of "flow of control" is why you can even do weird stuff like this -

def foo():
    return True
    whatIsThisIdontEven__somethingWeird.jpg  # would ordinarily throw RuntimeErrors anywhere else

print(foo())
# True

In your case, it entirely depends on your code flow at runtime, but you'll still end up encountering only one return, and consequently returning only once.

Note that one difference is in the case of try-except-finally, where the return in the final clause always wins.

def function():
    try:
        ... # do something
        return 1
    except SomeException:
        ... # do something else
    finally:
        return 2

In the case of normal execution, you'll encounter return 1 in try, but because of the semantics of the finally clause, you'd still end up returning 2. I believe this is the only exception.

Now, yield, on the other hand, is a different matter...

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Regarding the try/fail aspect - - is a `return` inside a try statement common? From your comment it seems like it's pointless and would (generally speaking) only be there by mistake or if you're learning. Or is there a reason to use a `return` within a try even if the `finally` has one too? – BruceWayne Mar 27 '18 at 17:14
0

Once the function sees a return statement, the function will end and return the variable in the return statement. So the rest of the function will not be executed once the function comes across a return statement.

0

The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something.

Keep in mind : function return one at a time by memory .

So when you start the loop and then 'if' condition goes true so function return and exit.

if List[i] == value:
    return i

and if you have to return many items then don't return the output instead of store the output in a list and return that list at last .

def find_value(List, value):

    return_list=[]

    for i in range(len(List)):
        if List[i] == value:
            return_list.append(i)


    return return_list

In you code you wanted two return so you can try conditional return like this:

def find_value(List, value):

    return_list=[]

    for i in range(len(List)):
        if List[i] == value:
            return_list.append(i)


    if return_list:
        return return_list
    else:
        return -1

print(find_value([1,2,3,4,5,6],4))
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88