Python how to reference variable
<p>I'm getting a problem when referencing variables on a python file. Here is the code:</p>

<pre><code>FG_E = 9
FG_R = 8
START = 7
READY = 9
MC = 3
BRAKE = 5
ERROR = 6
a = 2
b = 3

position = 0

def build_message(signal):
    message = position
    message = message | (0b1&lt;&lt;signal)
    s = bin(message)
    s = s[2:len(s)]
    s = (16-len(s))*'0' + s

    s0 = s[0:len(s)/2]
    s1 = s[len(s)/2:len(s)]
    s0 = s0[::-1]
    s1 = s1[::-1]
    s_final = int(s0 + s1, 2)
    position = s_final
    print bin(s_final)
    return s_final

build_message(FG_R)
</code></pre>

<p>The error I get is:
UnboundLocalError: local variable 'position' referenced berofe assigment</p>

<p>The problematic line is actually <code>position = s_final</code> in the function <code>build_message</code>.</p>

<p>If it wasn't there then <code>message = position</code> would work because the Python interpreter would know to which <code>position</code> variable you are referring. </p>

<p>But in this case it is ambiguous because you're are later reassigning to <code>position</code> (<code>position = s_final</code>). </p>

<p>You should either re think the design of the code, or add <code>global position</code> as the first line in <code>build_message</code>.  Keep in mind that as it says, it would make <code>position</code> a global variable and <code>build_message</code> will change the value of <code>position</code> every where throughout your code.</p>

<p><strong>EDIT</strong> A quick demo:</p>

<pre><code>global_var = 0

def foo1():
    print(global_var)

def foo2():
    print(global_var)
    global_var = 1

def foo3():
    global global_var
    print(global_var)
    global_var = 1
    print(global_var)

foo1()
&gt;&gt; 0

foo2()
&gt;&gt; UnboundLocalError: local variable 'global_var' referenced before assignment

foo3()
&gt;&gt; 0
   1
</code></pre>

python