Python:尝试调用函数时出现未定义变量错误? [英] Python: Getting an undefine variable error when trying to call a function?

查看:58
本文介绍了Python:尝试调用函数时出现未定义变量错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

了解 Python,它可能与缩进和排序有关.一开始我还以为是我调用了这个函数而没有先定义它,但是我换了好几次命令都没有结果.

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.

感谢答案!

推荐答案

unpackConfirm 定义在 unpackCon() 内部,超出了其他函数的作用域.您需要返回该变量才能访问它.

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.

试试:

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

这篇关于Python:尝试调用函数时出现未定义变量错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆