Python在循环外获取变量

ada*_*aam 4 python variables

我有一个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
Run Code Online (Sandbox Code Playgroud)

但我明白了 Nameerror: 'a' is not defined

NPE*_*NPE 6

错误消息表示您从未分配给a(即if从未评估过的条件True).

要更优雅地处理它,您应该a在循环之前分配一个默认值:

a = None
with open('test', 'r') as f:
   ...
Run Code Online (Sandbox Code Playgroud)

然后你可以检查它是否None在循环之后:

if a is not None:
   ...
Run Code Online (Sandbox Code Playgroud)