title: How to declare a variable outside an if statement
body: <p>Here is my code:</p>
  
  <pre><code>last_state={}
  last_device={}
  last_substate={}
  with open("TESTFILE.csv") as f:
      reader = csv.reader(f, delimiter=',')
      for row in reader:
          device = row[0]
          state = row[1]
          model = row[2]
          substate=row[3]
          #time = row[4]
          if device in row:
  
              if substate == 'Not joined' and model !='electric_meter':
                  if state == "Offline":
                      N_off = [device]
                     # print N_off, reader.line_num
  
                  if state == 'Online':
                      N_on = [device]
  
                  if N_off == N_on:
                      print device, reader.line_num
  </code></pre>
  
  <p>I am trying to compare the device ID of these 2 loops so that I only use the the ones that meet all criteria. Im not sure why but I get this error:</p>
  
  <pre><code>      `if N_off == N_on:
  NameError: name 'N_off' is not defined`
  </code></pre>
  
  <p>I am not very familiar with Python and how declaring variables works, but I tried to declare them globally and that gave me the same error. I understand it is because I am using <code>N_off</code> outside its scope, but I am not sure how to rectify that. </p>