Ham*_*ido -2 python recursion if-statement function
我有一个关于使用if语句和递归的函数调用的问题.我有点困惑,因为即使我的函数返回"False",python似乎也会跳转到if语句块
这是一个例子:
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)
Run Code Online (Sandbox Code Playgroud)
我的function_2返回"False",但python继续第5行的代码.谁能解释这种行为?提前感谢您的任何答案.
编辑:对不起,忘了括号
具体例子:
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
Run Code Online (Sandbox Code Playgroud)
在两个函数"isFieldFree"和"isFieldEscape"之后返回False python继续第5行中的代码,有时在第6行.
简短回答:
那是因为你实际上并没有调用这个函数.您可以使用括号调用该函数.
if function2():
...
Run Code Online (Sandbox Code Playgroud)
答案很长:
Python中的函数是一等公民(函数范例),因此仅仅通过名称来引用函数是完全有效的.以下是有效的语法:
def hello():
print("Hello")
hello_sayer = hello
hello_sayer() # print "Hello"
Run Code Online (Sandbox Code Playgroud)
现在的下一个概念是非布尔变量的真实性.在Python中,以下内容被视为False-y
其他一切都是真实的.由于函数名称不属于上述类别,因此在条件上下文中进行测试时,它被视为True-ish.
参考:https://docs.python.org/3/library/stdtypes.html#truth-value-testing
编辑:早期的问题是不完整的,没有函数调用.对于这个新问题,AChampion的回答是正确的.