python 函数递归调用_带有if语句的Python递归函数调用

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"

Here is an example:

1 def function_1(#param):

2 if function_2(#param):

3 #do something

4 if x

5 function_1(#different parameters)

6 if x>y:

7 function_1(#different parameters)

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.

edit: Sorry, forgot the brackets

concrete example:

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

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

解决方案

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):

. ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值