带有if语句的Python递归函数调用 [英] Python recursive function call with if statement

查看:394
本文介绍了带有if语句的Python递归函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用if语句和递归的函数调用有疑问. 我有点困惑,因为即使我的函数返回"False",python似乎仍会跳入if语句块

I have a question regarding function-calls using if-statements and recursion. I am a bit confused because python seems to jump into the if statements block even if my function returns "False"

这里是一个例子:

1    def function_1(#param):
2       if function_2(#param):
3           #do something
4           if x<y:
5               function_1(#different parameters)
6           if x>y:
7               function_1(#different parameters)

我的function_2返回"False",但是python例如在第5行继续执行代码.谁能解释这种行为?预先感谢您提供任何答案.

My function_2 returns "False" but python continues the code on line 5 for example. Can anyone explain this behavior? Thanks in advance for any answers.

对不起,忘记了括号

具体示例:

1    def findExit(field, x, y, step):
2        if(isFieldFree(field, x, y)):
3            field[y][x] = filledMarker
4            findExit(field, x + 1, y, step+1)
5            findExit(field, x - 1, y, step+1)
6            findExit(field, x, y + 1, step+1)
7            findExit(field, x, y - 1, step+1)
8        elif(isFieldEscape(field, x, y)):
9            way.append(copy.deepcopy(field))
10            wayStep.append(step+1)

    def isFieldFree(field, x, y):
        if field[y][x] == emptyMarker:
            return True
        else:
            return False

    def isFieldEscape(field, x, y):
        if field[y][x] == escapeMarker:
            return True
        else:
            return False

在两个函数"isFieldFree"和"isFieldEscape"都返回False之后,python继续执行第5行中的代码,有时在第6行中.

After both functions "isFieldFree" and "isFieldEscape" return False python continues the code in line 5 sometimes in line 6.

推荐答案

您可能会误解递归的工作原理,是的,它在第5行或第6行继续,因为递归已在调用堆栈的较低级别结束,因此它在调用堆栈中的更高级别.这是一个示例调用堆栈,请注意False之后的下一个操作是更高调用堆栈中的下一个findExit():

You may misunderstand how recursion works, yes it continues at line 5 or 6 because the recursion has ended at a lower level in the call stack, so it continues at a higher-level in the call stack. Here's a sample call stack, note the next operation after False is the next findExit() at the higher call stack:

1 findExit(...):
2    True:
3        field assignment
4.1      findExit(x+1) 
  2          True
  3              field assignment
  4.1            findExit(x+1):
    2                False  # Does not jump to line 5 in current call stack.
  5.1            findExit(x-1):
    .                ...

这篇关于带有if语句的Python递归函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆