1

Why the variables a, c, d have not changed, but b has changed?

a = 0
b = []
c = []
d = 'a'


def func_a(a):
    a += 1
    
    
def func_b(b):
    b += [1]
    
    
def func_c(c):
    c = [2]
    
    
def func_d(d):
    d += 'd'
    
    
func_a(a)
func_b(b)
func_c(c)
func_d(d)
print('a = ', a)
print('b = ', b)
print('c = ', c)
print('d = ', d)

I think it has to do with the fact that all variables are global, but I don't understand why b changes then..

Jose Kadur
  • 19
  • 1
  • 1
    https://nedbatchelder.com/text/names.html is the best explanation of how Python names work I know of – chthonicdaemon Nov 30 '22 at 12:06
  • Variables a and d are immutable so you're passing them by value and the "change" is only taking place within the function – DarkKnight Nov 30 '22 at 12:09
  • "I think it has to do with the fact that all variables are global" No; **none** of them are global. Each function reads `a`, `b`, `c` or `d` respectively from its *parameter*, which is inherently local. This is a question about **pass by reference**, so I have linked the appropriate canonical. – Karl Knechtel Nov 30 '22 at 12:30

2 Answers2

0

This is related by local and global scope, you can update using change the name of function parameter names;

a = 0


def func_a(local_a):
    global a
    a += 1

func_a(a)
print('a = ', a)
# output: a =  1

"global a" meaning this function will use the global scope of a.

If you try to use with this way;

a = 0
b = []
c = []
d = 'a'


def func_a(a):
    global a
    a += 1

func_a(a)
print('a = ', a)

You will get an error like this;

  File "glob_and_local.py", line 8
    global a
    ^^^^^^^^
SyntaxError: name 'a' is parameter and global

Because same names are conflicting.

Sezer BOZKIR
  • 534
  • 2
  • 13
0

Here, a, b, c, d are global variables.

For a: a is an integer. when you are calling func_a(a) you are only making changes in the local scope but not returning anything. That's why there is no change in the global variable a. Same thing happening with global variables c and d.

For b:

You are passing an array and appending an array into it. append method makes changes in global variables too.

NOTE:

here, b += [1] is equivalent to b.append(1)

Ashutosh Yadav
  • 333
  • 1
  • 12