从另一个def块中的def块引用变量

时间:2018-09-21 19:40:54

标签: python

基本上,我有这段代码,如下所示:

def start():

def blockA():
    y = 3
    x = 4
    print("hello")
blockA()

def blockB():
    if x !=y:
        print("not the same")
blockB()
start()

但是,这给我一个错误,指出未定义x和y。我该如何在blockB中引用x和y变量?

1 个答案:

答案 0 :(得分:1)

您需要在blockA函数中返回变量,然后在第二个函数中调用该函数。

def blockA():
    y = 3
    x = 4
    print("hello")
    return x,y


def blockB():
    x,y=blockA()
    if x !=y:
        print("not the same")

这应该对您有用。

相关问题