lifelonglearner
lifelonglearner

Reputation: 326

How do return statements work within a function? Can I use multiple return statements?

The following code returns "True."

check = [1,2,4,6]

def is_consecutive(a_list):
    """Checks to see if the numbers in a list are consecutive"""
    total = 2
    while total > 1:
        test = a_list.pop(0)
        if test == a_list[0] - 1:
            total = len(a_list)
            return True
        else:
            return False
            break

works = is_consecutive(check)
print(works)

I found a solution, by moving return True to a new block, after the while loop:

check = [1,2,4,6]

def is_consecutive(a_list):
    """Checks to see if the numbers in a list are consecutive"""
    total = 2
    while total > 1:
        test = a_list.pop(0)
        if test == a_list[0] - 1:
            total = len(a_list)
        else:
            return False
            break
    return True

works = is_consecutive(check2)
print(works)

I don't understand fully why moving this piece of code outside the while loop works correctly. It seems to me that once you tell a function to return True, that cannot be changed later on in the function. Is that correct?

Upvotes: 2

Views: 476

Answers (3)

sahasrara62
sahasrara62

Reputation: 11238

This is because in new code, you are trying to find a condition where you will get number in the list are non consecutive. If you find any number then you immediately return false.

Once going through the list and no consecutive numbers are found, it is taken as list is of consecutive numbers and hence return True.

Upvotes: 0

Bibek
Bibek

Reputation: 71

Return statement stops the execution of that particular function. And yes you can use multiple return statement but only inside conditional blocks. Because when return statement is called it will stop execution of that function so it will not be able to proceed to lines/block after the return statement.

Upvotes: 2

jafuweze
jafuweze

Reputation: 63

Yes, when you do return True, you are "quitting" the function from then on, i.e. nothing else in the function will be executed. By moving return True outside the while loop and to the end of the function, it makes sure that the function never returns False if the list is consecutive, and thus must return True.

Upvotes: 1

Related Questions