Reputation: 69
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]
Upvotes: 0
Views: 38
Reputation: 782489
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.
Upvotes: 2
Reputation: 183
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)
Upvotes: 1