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?
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.
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.
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.
精彩评论