Low Orbit Flux Logo 2 F

Python How To Exit A Function

To exit a function in Python just call return. If you have an actual value to return you can do so like this.


return 4

If you don’t have a value to return you could just use either of these two lines to return nothing. They do exactly the same thing.


return None
return

If a function continues until the end without returning anything it will then return None.

Here is an example of a function that calls return in different places. Note that any one of these calls will result in the function exiting.


def test1(x):
    if x > 50:
        return "big"
    elif x < 10:
        return "small"
    return "medium"

Here is another example of almost the same thing except that it doesn’t include a default return value. Any value passed between 10 and 50 will result in the function continuing until the end where it will then return “None” by default when it completes.


def test1(x):
    if x > 50:
        return "big"
    elif x < 10:
        return "small"