title: Sending data over serial in python from different functions
body: <p>I program in C++ and C# normally and am trying to get accustomed to how python works so forgive me if this is a fairly basic question.</p>
  
  <p>I'd like to open a serial connection in python over RS-232 and send data from various functions. Here's the functions that I have to open a serial port and send data:</p>
  
  <pre><code>def sendData(data):
      ser = serial.Serial('/dev/ttyUSB0', 115200)
      data += "\r\n"
      ser.write(data.encode())
  </code></pre>
  
  <p>Pretty simple, but I'd like to move the <code>ser = serial.Serial('/dev/ttyUSB0', 115200)</code> line outside the function so that I can just call this function on it's own.</p>
  
  <p>Now in other languages I would just make the ser variable public so that other functions could access it, but I'm not sure I'm understanding how variables work in python properly yet. Ideally I'd like something like this:</p>
  
  <pre><code>def main():
      ser = serial.Serial('/dev/ttyUSB0', 115200)
      while 1:
          #misc code here
          sendData(data)
  </code></pre>
  
  <p>I know I could pass the ser variable through the function call and make it sendData(ser, data), but that seems unnecessary. What's the best way to do this?</p>
  
  <p>Thanks!</p>