Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is the difference between accessing the name and <a href="http://docs.python.org/reference/executionmodel.html" rel="noreferrer">binding</a> it within a scope.</p> <p>If you're just looking up a variable to read its value, you've got access to global as well as local scope.</p> <p>However if you assign to a variable who's name isn't in local scope, you are <em>binding</em> that name into this scope (and if that name also exists as a global, you'll hide that). </p> <p>If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.</p> <p>Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).</p> <pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; def p(): print(a) # accessing global scope, no binding going on &gt;&gt;&gt; def q(): a = 3 # binding a name in local scope - hiding global print(a) &gt;&gt;&gt; def r(): print(a) # fail - a is bound to local scope, but not assigned yet a = 4 &gt;&gt;&gt; p() 1 &gt;&gt;&gt; q() 3 &gt;&gt;&gt; r() Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; r() File "&lt;pyshell#32&gt;", line 2, in r print(a) # fail - a is bound to local scope, but not assigned yet UnboundLocalError: local variable 'a' referenced before assignment &gt;&gt;&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload