我对Python还是很陌生,但是似乎遇到了问题。尝试调用定义该变量的另一个函数时,出现未定义的错误。

def unpackCon():
    unpackConfirm = input("Unpack contents?[Y/N] ")

def unpackConScript():
    if unpackConfirm == "y":
        print ("Unpack confirmed.")
    elif unpackConfirm == "n":
        print ("Unpack unconfirmed.")
    else:
        print ("Value %s is not valid.") % (unpackConfirm)
        unpackCon()

unpackCon()
unpackConScript()


了解Python,它可能与缩进和排序有关。起初我相信是因为我没有先定义函数就调用了函数,但是我多次切换顺序却没有结果。

欣赏答案!

最佳答案

unpackConfirmunpackCon()内部定义,并且在其他函数中超出范围。您需要返回变量才能访问它。

尝试:

def unpackCon():
    unpackConfirm = input("Unpack contents?[Y/N] ").lower()
    return unpackConfirm

def unpackConScript():
    unpackConfirm = unpackCon()

    if unpackConfirm == "y":
        print ("Unpack confirmed.")
    elif unpackConfirm == "n":
        print ("Unpack unconfirmed.")
    else:
        print ("Value %s is not valid.") % (unpackConfirm)
        unpackCon()

unpackConScript()

09-12 16:50