title: Python 2.7 global variables?
body: <p>I have some code which attempts to write to a socket (ardSocket), and if it throws an exception it will try to reconnect. I declared the socket variable as global so that when assigned in the separate function, it should still be accessible to the rest of the program, but for some reason still throws an exception. When I declare the actual socket globally at the beginning of the code, everything works fine. Why can't I declare  ardSocket=None globally, then assign it for use in a separate function?</p>
  
  <pre><code>#!/usr/bin/env python
  '''
  Arduino LED values: 0=down, 1=up, 2=blink
  '''
  import os
  from subprocess import Popen, PIPE, STDOUT
  import serial
  import time
  
  ardSocket = None
  
  def ardConnect():
      arduinoFound=False
  
      while arduinoFound==False:
          try:
              ardSocket=serial.Serial('/dev/ttyUSB0',9600)
              arduinoFound=True
              print "Arduino connected"
          except:
              print "Arduino not found. retrying in 10 seconds"
              time.sleep(10)
  
  while 1==1:
      response=Popen(['ping','-c 1','google.com'],stdout=PIPE,stderr=STDOUT)
      stdout,nothing=response.communicate()
  
      if "Name or service not known" in stdout:               #If DNS fails
          try:
              ardSocket.write('0')                                #Solid RED LED
          except:
              ardConnect()
  
      else:
          pingTestArray=stdout.splitlines()                   #Split ping output into array by lines
          pingTestArrayList=pingTestArray[4].split(" ")       #Split the line containing packet loss by words
          packetLoss=pingTestArrayList[5].replace('%','')     #Remove the % from the element containing packet loss number
                                                              #and assign value to packetLoss var
  
  
          if int(packetLoss) &gt; 30 and int(packetLoss) &lt; 95:   #If packet loss &gt; 30% &amp;&amp; &lt; 95% warn, FLASH RED LED
              try:
                  ardSocket.write('2')
              except:
                  print "ard error"
                  ardConnect()
          elif int(packetLoss) &gt; 94:                          #Network is down, &gt;95% packet loss, SOLID RED LED
              try:
                  ardSocket.write('0')
              except:
                  print "ard error"
                  ardConnect()
          else:
              try:
                  ardSocket.write('1')                            #Else show good, GREEN LED
              except:
                  print "ard error"
                  ardConnect()
      time.sleep(5)
  </code></pre>