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>This blog post(<a href="http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/" rel="nofollow">1</a>) explains the parameter passing of Python.</p>

<p>When you declare b in example 1 you declared it globally.</p>

<p>In example two you overwrite the name b so it is only known in func2 and thats why func1 does not know any b.</p>

<p>Hope this helps :)</p>

python