""" If you define a variable outside of a function before running the function, it does not get updated by the function when used. They are totally separate. The only way to update it is to explicitly define its value outside of the function. This contrasts with C, wherein a variable can be defined outside of a function, and then be updated within one. HOWEVER, a variable can be defined as global, and then it will work. But that's considered bad practice in most situations, so don't... ALSO, methods (such as list.append(1) or using list[0]=1) will work on lists outside of a function, without declaring that list to be global. This is because these do not rebind the list, but instead find the list in global space and act on it. """ # TYPICAL CASE x = 1 def fun1(): x = 2 fun1() #x is still 1 because not global print x def fun2(): x = 2 return x fun2() #the output of fun2 was not saved anywhere; the value of x is still 1 print x x = fun1() #fun1 has no returned output, so x is now nothing print x x = fun2() #FINALLY, x is now 2 because it has been directly updated print x # GLOBAL CASE x = 1 print x def fun3(): global x x = 2 fun3() #because x was declared global within the function, it can update it outside of itself print x # LIST METHOD CASE y = [1,2,3,1] a=0 def fun4(): y[3] = 4 #changing a list entry is like calling a member function on the list; it will affect it a = 1 #directly rebinding the variable "a" creates a local binding separate from the global one; #unless "global" is used, of course fun4() print y #will have new value at index 3 print a #will be the same old value of "a" def fun5(): y.append(5) #like changing a list entry, this will find the list in global space and affect it fun5() print y
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question