Weird namespace behaviour
<p>When trying to run the following code:</p>

<pre><code>i = 0
def truc():
    print (i)
    if (False): i = 0
truc()
</code></pre>

<p>it yields an UnboundLocalError, but</p>

<pre><code>i = 0
def truc():
    print (i)
    #if (False): i = 0
truc()
</code></pre>

<p>doesn't.</p>

<p>Is that a wanted behaviour ?</p>

<p>Is there a way to modify the value of a variable without creating a new one ? I could use a dict of one element. It works but it seems ugly:</p>

<pre><code>i = {0 : 0}
def truc():
    print (i[0])
    if (False): i[0] = 0
truc()
</code></pre>

<p>Isn't it a better solution ?</p>

<p>just add</p>

<pre><code>global i
</code></pre>

<p>at the beginning of the method <code>truc()</code> to declare that <code>i</code> is global variable</p>

<pre><code>def truc():
    global i
    if (False):
        i = 0
</code></pre>

<p>Take a look at this <a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">topic in Python's FAQ</a> to get more informations</p>

python