mikey555
mikey555

Reputation: 454

exiting a Python function call

How can my program exit a function call? I have a recursive function that, when a condition is satisfied, calls itself.

def function( arg ):
    if (condition):
        ...
        return function( arg + 1 )

My guess at how it works: if the condition is not satisfied, the function call will terminate. In my program, that doesn't seem to be the case -- the condition is violated but the program jumps to the return statement (perhaps the only return statement it sees?).

Is there some sort of exit() that I could put in an else clause?

Upvotes: 1

Views: 15916

Answers (3)

tom10
tom10

Reputation: 69182

As listed, your code will always just return None. It goes through all the recursion, and does this until the condition is not met, and then drops out the end of the function and returns None.

For example, try this:

def f(x):
    if (x<10):
        return f(x+1)
    return x

and build up from this to do something useful.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

A "function terminating" results in it returning None. If you are seeing something different then it may very well be hitting the return you see, because it may be mis-indented. Use python -tt myscript.py to verify that you haven't mixed tabs and spaces.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

If a Python function does not explicitly return a value, it returns None. That implicit return None is analagous to return in C like languages.

Upvotes: -1

Related Questions