gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:21:23 26 4
gpt4 key购买 nike

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

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

在下面的代码中我需要访问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

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

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

最佳答案

if block 之前使用None定义变量,然后在if block 中更新它。考虑以下因素:

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

关于python - 当变量在python的if条件中定义时,如何访问if条件后的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54630146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com