开发者

exiting a Python function call

开发者 https://www.devze.com 2023-04-03 19:41 出处:网络
How can my program exit a function call? I have a recursive function that, when a condition is satisfied, calls itself.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消