我有一个python代码,我需要在for循环和if语句之外获取其值,然后进一步使用该变量:
我的代码:
with open('text','r') as f:
for line in f.readlines():
if 'hi' in line
a='hello'
print a #variable requires outside the loop
但是我明白了 Nameerror: 'a' is not defined
错误消息表示您从未分配给您a
(即,if
条件从未评估为True
)。
为了更优雅地处理此问题,应a
在循环之前将默认值分配给:
a = None
with open('test', 'r') as f:
...
然后,您可以检查它是否None
在循环之后:
if a is not None:
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句