I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors
ex1:
def func1():
a = 1
b.add('b')
a = 0
b = set()
func1()
print(a,b)
the result is 0 {'b'}
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?
ex2:
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 <module>
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
why in this case, b cannot be assigned in func1()?
ex3:
I have to pass the variable from function to function
def func1(b):
b.add('b')
def func2():
b = set()
func1(b)
print(b)
func2()
it prints {'b'} this time
ex4:
what I can also do is to define b outside
def func1():
b.add('b')
def func2():
func1()
print(b)
b = set()
func2()
it prints {'b'} as well
thanks in advance for your kind help