Home > other >  Changing a variable of one function from another function
Changing a variable of one function from another function

Time:09-19

Is there a way to change a variable inside function A from function B when function A called function B

For example:

def a():
     flag = False
     b()
     print(flag)

def b():
     flag = True

I would like flag == True

another example:

def a():
    list = [1,2,3]
    b():
    return list

 def b():
    list.append(4)

CodePudding user response:

The flag variable is locally scoped to function A and B. This does not mean that they are the same variable. They're completely different from each other, occupying a completely different address space all together.

If you would like function B to change the value of your flag variable in function A, you can simply have function B return the value.

def b():
   flag = True 
   return flag

Another method is to use pass by reference, which allows you to alter the value of the variable in that memory address space. This only works for mutable objects. In this case, a boolean is immutable so a pass by reference isn't possible here.

CodePudding user response:

you need to pass it either as a parameter to the function or create a global variable (usually considered to be bad style)

flag = False


def a(): 
    b()
    print(flag)


def b():
    global flag
    flag = True
    
a()  # True
  • Related