user2425814
user2425814

Reputation: 409

What's the point of the return in this code?

So, I have this function below:

def remove_all(lst):
    i = 0
    while i < 10:
        try:
            print('Removing... ')
            print(int(lst.pop()) + 10)
            print("Removed successfully.")

        # As soon as an IndexError is raised, jump to the following block of code...        
        except IndexError as err: 
            # if you encounter an indexerror, do the following:
            print("Uh oh! Problems.")
            return

        #As soon as a Value error is raised, jump here.
        except ValueError as err:
            print("Not a number")

        i = i + 1

What does the return do? There is no value after the return, so does it mean None or True? And what is the point of having the return there if the value is none?

Thanks!

Upvotes: 0

Views: 113

Answers (4)

Dennis Geisse
Dennis Geisse

Reputation: 81

In your example, there is no return value.

Given you would call the function like this:

a = remove_all(lst)

a will be None because the function simply returns nothing.

To check the success of the function, you could implement it like this:

def ....
    try:
        ...
    exception 1:
        your error handling...
        return False
    exception 2:
        your error handling...
        return False

    continue function...
    return True

When you then check the return value of your function, you will see if it has been executed till the end (True) or if it raised an error before (False).

However, this will not continue the execution of this particular function after one of the defined errors occurred.

Upvotes: 0

icedwater
icedwater

Reputation: 4887

This causes the function to exit when an IndexError is encountered, just without returning any value.

Upvotes: 0

SheetJS
SheetJS

Reputation: 22925

The return value is None.

In this context, the function never returns a value. The point of the return is to stop execution

Upvotes: 7

lordkain
lordkain

Reputation: 3109

The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, you could exit/stop the function.

Upvotes: 0

Related Questions