Python3: 一个函数内调用另一个函数,怎么办?

Python3: Calling a function within a function to another function, how?

这是一个代码示例

import random
def randomNum():
    i = random.randint(1,10)
    return i

这只是为了添加上下文

下面是问题所在

def function1():
    randomNum()
    r = randomNum()
    if r = 2:
        #do something
        def function2():
            return True

这是函数 1 中的函数 2,我想在函数 3 上调用它

def function3():
    #some code
    function = function2()
    if function == True:  #this last 2 lines is what i'm trying to achieve
        #do something

建议?

问题是function1 returns None,但应该return function2。在 function3 中只需检查 if function is not None: 所以,像这样:

In [1]: import random
   ...: def randomNum():
   ...:     i = random.randint(1,4)
   ...:     return i
   ...:
   ...: def function1():
   ...:     randomNum()
   ...:     r = randomNum()
   ...:     print(r)
   ...:     if r == 2:
   ...:         #do something
   ...:         def function2():
   ...:             return True
   ...:         return function2
   ...:
   ...: def function3():
   ...:     function = function1()
   ...:     if function is not None:
   ...:         print("Did stuff")
   ...:     else:
   ...:        print("didn't do stuff")
   ...:

进行中:

In [2]: function3()
4
didn't do stuff

In [3]: function3()
1
didn't do stuff

In [4]: function3()
3
didn't do stuff

In [5]: function3()
4
didn't do stuff

In [6]: function3()
3
didn't do stuff

In [7]: function3()
2
Did stuff

In [8]: function3()
4
didn't do stuff

In [9]: function3()
2
Did stuff