python - 当变量在python的if-condition中定义时,如何在if-condition之后访问变量
问题描述
当在 python 的 if 条件中创建变量时,我需要从 if 条件之外访问变量。if-condition 中的变量类型是test
is<type, str>
和vn
is <type, instance>
。
我尝试了以下方法,但它对我不起作用。
在下面的代码中,我需要访问vn
和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)
推荐阅读
- vue.js - 无法访问组件 nuxt 中的 process.env 变量
- python - 从不同主机的注册变量创建字典
- javascript - 带有ajax调用的Javascript循环生成相同的JSON?
- python - 如何在 Python3 中将异步生成器流转换为类似文件的对象?
- html - 为什么 WordPress 在 URL 中编码 & 符号?
- android - Kotlin:当块作为最后一条语句时是否可以抛出异常?
- python - 在python脚本中提取json数据时出现KeyError用户名
- asp.net - 将文件上传到 UploadAsync 方法的 s3 存储桶 asp.net 核心时出现错误“访问被拒绝”
- c# - 我使用 openXML 为 Powerpoint 段落设置的字体大小没有被使用
- android - Android SensorDirectChannel 不返回传感器测量值