Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么函数不';嵌套函数中的else语句之后是否返回?_Python_If Statement_Return_Conditional Statements_Nested Function - Fatal编程技术网

Python 为什么函数不';嵌套函数中的else语句之后是否返回?

Python 为什么函数不';嵌套函数中的else语句之后是否返回?,python,if-statement,return,conditional-statements,nested-function,Python,If Statement,Return,Conditional Statements,Nested Function,我不知道为什么,但是这个函数没有返回它应该返回的2。但当我们这样做时: def test1(): def test2(): if False: return 1 else: return 2 test2() 它在屏幕上打印2。 为什么会这样 PS:我知道如果if条件为False,我们不需要这个else返回2。但我很好奇,因为如果我们使用这个test2作为非嵌套函数,它将毫无问题地返回2。test1调用test2,但它本身不

我不知道为什么,但是这个函数没有返回它应该返回的2。但当我们这样做时:

def test1():
    def test2():
        if False:
            return 1
        else: return 2
    test2()
它在屏幕上打印2。 为什么会这样


PS:我知道如果if条件为
False
,我们不需要这个
else
返回2。但我很好奇,因为如果我们使用这个test2作为非嵌套函数,它将毫无问题地返回2。

test1
调用
test2
,但它本身不返回任何内容,因此隐式返回
None
。您似乎打算将调用返回到
test2

def test1():
def test2():
如果为假:
返回1
其他:
返回2
返回test2()#这里!

test2()
更改为
returntest2()
函数调用接收返回函数到本地作用域的返回值。如果你想让它返回当前范围之外,你也必须返回它。你需要
returntest2()
,因为
test1
*不返回任何内容,所以默认情况下它将返回
None
def test1():
    def test2():
        if False:
            return 1
        else: print(2)
    test2()