当变量在python的if条件中定义时,如何访问if条件后的变量

2024-01-19

当变量在 python 的 if 条件内部创建时,我需要从 if 条件外部访问变量。 if 条件内的变量类型是test is <type, str> and vn is <type, instance>.

我已经尝试过以下方法,但它对我不起作用。

在下面的代码中我需要访问vn and test变量

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

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

它抛出以下错误。AttributeError: 'NoneType' object has no attribute 'firstChild'


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

y = None
x = 1
print(y)
if x == 1:
    y = "d"
else:
    y = 12
print(y)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当变量在python的if条件中定义时,如何访问if条件后的变量 的相关文章

随机推荐