简体   繁体   中英

Python: Getting an undefine variable error when trying to call a function?

I'm still pretty new to Python, but it seems I've run into a problem. I get an undefined error when trying to call another function that defines that variable.

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()

Knowing Python, it's probably got something to do with indentation and the sorts. At first I believed it was because I called the function without defining it first, but I switched around the orders a bunch of times with no result.

Appreciate an answer!

unpackConfirm is defined inside of unpackCon() , and is out of scope in the other function. You need to return the variable in order to access it.

try:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM