简体   繁体   中英

Change global variable whenever the function called

Could someone please explain to me how could I change the value of x to "didn't work" whenever the globallyChange() function is called? Thank you very much!

def globallyChange():
    x = "didn't work"

def main():
    global x
    x = 10
    globallyChange() #Call the function for changes.
    print(x)

main()

CURRENT OUTPUT: >> 10

I have tried the same thing with list/array being the global variable, and when the globallyChange() function is called, it actually DID change the global variable list. I was wondering how it is different between an integer/string/bool global variable and list global variable?

def globallyChange():
    lst.append(1)
    lst.append(5)
    lst.append(7)

def main():
    global lst
    lst = []
    globallyChange() #Call the function for changes.
    print(lst)

main()

OUTPUT: >> [1,5,7]

You need to put a global declaration in all functions that assign to the variable. So it should be:

def globallyChange():
    global x
    x = "didn't work"

The reason you don't need this in the version with the list is that you're not assigning to the variable. You're just reading the variable; which automatically looks for a global variable if no local variable can be found. append() doesn't assign to the variable, it modifies the list in place.

You need to define x as a global variable in all functions that refer to it. Otherwise python creates a new local variable.

Try this:

x = 0
def globallyChange():
    global x
    x = "didn't work"

def main():
    global x
    x = 10
    globallyChange() #Call the function for changes.
    print(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM