简体   繁体   中英

How does the return function work within a loop and procedure?

I thought a for-loop would run through all the elements in a list regardless of the conditions of the loop.
For the problem below-I would expect the printed output to be 6,-1,
the last position where p[count]==n and then my return statement after the loop ends.

When if p[count]==n finds a match, does the loop and procedure keep running past my return function?
Does someone have a good explanation of how this works?

def find_element(p,n):
    count=0
    for x in p:
        if p[count]==n:
            return count
        count=count+1
    return '-1'

print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')

When executing a function the first return statement encountered will end the function, and the result of the expression given to the return statement will be given back to the caller. In this case, when p[count] == n is True , the count will be returned. The function will only return -1 if the for x in p: loop is exhausted without ever finding the appropriate element.

All that being said however the loop you have doesn't quite behave the way the function suggests it should.. If you are hoping to find the list of every index which has the value n you will want something like this:

def find_element(p,n):
    return [i for i,x in enumerate(p) if x == n]

print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')
#[1, 3, 4, 6]

Functions can only call return one time. As pointed out in the comments this returns from the function to the caller. Thus the rest of the code does not run.

If you want to return all of the relevant indices you can either:

  1. Keep track of the indices in a list and just return the list at the end of the function

  2. Look into generators and use the yield keyword

Say you typically run 10 laps around a track after work but your boss calls you after the 4th lap and says "we have an emergency and need you to return to work right away" then the imperative to return will override the imperative to complete the laps (at least if you want to be a good employee). Return -- not the if statement per se -- is what caused your loop to end.

Your first question: "When if p[count] == n finds a match, does the loop and procedure stop running?"

The answer is no. The program exits the find_element function when it hits any return statement. In your case, either return count , or return -1 .

What you are concerned about is called "Flow Control".

For loops are a form of flow control that give you the ability to do repetition. If/(then)/Else is another form to do decisions.

The python docs (chapter 4) have a good introduction to this.

These statements can break out of a loop:

  1. The return statement.
  2. The break statement.

At run-time, the loop can also be broken if an unhandled exception occurs within it.

A related flow is implemented using the continue statement. If you are part-way into an iteration of the loop, continue will skip the rest of the iteration and proceed to the next one.

In your particular example, the if statement occurs within the context of a loop which is within the context of a function. The return statement takes us not only out of the loop, but out of the function and sets the value returned by the function.

The return aborts all further activities within the function and returns control to the caller. (as juanchopanza said)

Incidentally, you don't need to keep two separate variable count and x . They are redundant. Do this instead:

def find_element(p,n):
    try:
        return p.index(n)
    except ValueError:
        return -1

It works:

>>> print find_element(['1', '2', '1', '2', '2', '1', '2'],'2')
1
>>> print find_element(['1', '2', '1', '2', '2', '1', '2'],'4')
-1

What your for loop is trying to do is check if p[count] is equal to n and if so, stops and exit the loop and your function ends and returns the current value of count . But if it doesn't find a match, the loop exits anyway and your function will return -1 .

Also, you could/should use count += 1 to increment count.

In Python, as is all (most) languages, a return does return (sic) the value AND terminate the function (or procedure, as is it called in the question; but function, or calleble is more correct).

Python does however, has an option to separate them. By using ' yield ': that will return the value, but (kind of) continues the loop. Note: the function (or generator/iterator) has to be called in a loop, to return (yield) each value, one by one.

This is a bit advanced, so I leave it to the reader to lookup the documentation and good examples

Last remark: using a count er, as shown is not pythonic ! Use enumerate helper instead.

def find_element(p,n):
    for count, elm in enumerate(p):  # p is a list or sequence 
        if elm == n                       # maybe 'is' is better as '=='
            return count
    return -1                               # however, returning None is  more Pythonic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM