当变量在python中的ifcondition中定义时,如何访问ifcondition之后的变量

2024-10-04 09:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

当变量在python的if条件内创建时,我需要从if条件外部访问变量。if条件中的变量类型是test<type, str>,而{}是{}。在

我试过下面的方法,但没用。在

在下面的代码中,我需要访问vntest变量

for DO in range(count) :
    atnnames = doc.getElementsByTagName("atnId")[DO]
    atn = atnnames.childNodes[0].nodeValue
    if atn == line[0]:
        vn = doc.getElementsByTagName("vn")[DO]
        vncontent = vn.childNodes[0].nodeValue
        y = vncontent.encode('utf-8')
       # print y
        if '-' in y:
            slt = (int(y.split('-')[0][-1]) + 1)
            test = y.replace(y.split('-')[0][-1], str(slt))
       #     print test
        else:
            slt = (int(y.split('.')[-1]) + 1)
            test = y.replace(y.split('.')[-1], str(slt))
       #     print test
    else:
        #print test
        vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

当我运行上面的代码时得到的错误是

UnboundLocalError: local variable 'test' referenced before assignment

我尝试在for循环之前将变量定义为None。在

这是在错误之下。 AttributeError: 'NoneType' object has no attribute 'firstChild'


Tags: 代码intestforif条件dosplit
2条回答

Noneif块之前定义变量,然后在if块中更新它。考虑以下因素:

y = None
x = 1
print(y)
if x == 1:
    y = "d"
else:
    y = 12
print(y)

您的问题似乎是您引用的变量超出了它的范围。本质上,所发生的事情是在if语句中,您正在创建一个专用于if范围内使用的变量。实际上,当你说print vn.firstChild.nodeValue时,你也可以把它想象成任何其他变量,比如print undefinedVar。所发生的是你在变量被定义之前引用(调用)。在

不过,这里不用担心,因为这很容易修复。我们所能做的就是简单地创建您的vn并在if范围之外测试变量,因此在实际方法内部执行以下操作:

vn = None
test = None

for DO in range(count) :
    atnnames = doc.getElementsByTagName("atnId")[DO]
    atn = atnnames.childNodes[0].nodeValue
    if atn == line[0]:
        vn = doc.getElementsByTagName("vn")[DO]
        vncontent = vn.childNodes[0].nodeValue
        y = vncontent.encode('utf-8')
       # print y
        if '-' in y:
            slt = (int(y.split('-')[0][-1]) + 1)
            test = y.replace(y.split('-')[0][-1], str(slt))
       #     print test
        else:
            slt = (int(y.split('.')[-1]) + 1)
            test = y.replace(y.split('.')[-1], str(slt))
       #     print test
    else:
        #print test
        vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

这基本上只是在最外面的范围内创建一个空变量。我将这些值设置为None,因为它们是在for循环运行后定义的。所以现在的情况是,有一个变量已经在外部声明,并且在开始时是None,但是当您运行for循环时,您并不是在if语句内部创建一个临时变量,而是实际上更改了

相关问题 更多 >