Namespace questions: Mutable variable doesn't need to be declared as global in function?
<p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>

<p><strong>ex1:</strong></p>

<pre><code>def func1():
    a = 1
    b.add('b')

a = 0
b = set()
func1()
print(a,b) 
</code></pre>

<p>the result is 0 {'b'}</p>

<p>Neither a nor b is declared as global, but assignment to b has changed the global value of b, is it because b is mutable variable? </p>

<p><strong>ex2:</strong></p>

<pre><code>def func1():
    b.add('b')

def func2():
    b = set()
    func1()

func2()
print(b)

Traceback (most recent call last):
Â  File "test_variables.py", line 10, in &lt;module&gt;
Â  Â  func2()
Â  File "test_variables.py", line 8, in func2
Â  Â  func1()
Â  File "test_variables.py", line 4, in func1
Â  Â  b.add('b')
NameError: name 'b' is not defined
</code></pre>

<p>why in this case, b cannot be assigned in func1()? </p>

<p><strong>ex3:</strong></p>

<p>I have to pass the variable from function to function </p>

<pre><code>def func1(b):
    b.add('b')

def func2():
    b = set()
    func1(b)
    print(b)

func2()
</code></pre>

<p>it prints {'b'} this time</p>

<p><strong>ex4:</strong></p>

<p>what I can also do is to define b outside</p>

<pre><code>def func1():
    b.add('b')

def func2():    
    func1()
    print(b)

b = set()
func2()
</code></pre>

<p>it prints {'b'} as well</p>

<p>thanks in advance for your kind help </p>

<p>What your asking about is called scope.  Scope is a generic name for what's defined where. So when you declare a variable:</p>

<pre><code>b = 0
</code></pre>

<p>anything at the same level of scope, or lower can see its definition.</p>

<pre><code>b = 1
def func():
    print(b)

func()
</code></pre>

<p>This works because b has already been defined in that scope, in this instance b is global(everything can see its definition).</p>

<pre><code>def func():
    b = 0

def func1():
    print(b)

func()
func1()
</code></pre>

<p>This will not work because b is now a local variable, its only defined in func(), not func1()</p>

<pre><code>b = 1
def func():
    b = 0

def func1():
    print(b)

func()
func1()
</code></pre>

<p>This will print 0 because b was defined at a global level. Setting a global variable to a new value, no matter where you do that, will always make that new value available globally</p>

<p>But you also have to consider ordering.</p>

<pre><code>print(b)
b = 1
</code></pre>

<p>will not work</p>

<pre><code>b = 1
print(b)
b = 0
</code></pre>

<p>Will print b = 1 because the value wasn't set to 0, before being print</p>

python