Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 26 Online
OpenStudy (anonymous):

In python when I refer to a variable inside a function, how does it defers local variables from global ones? In one video I saw the professor using 'gobal var' to access global variables and accessing without the global reference it used local variable, while in another video he just used a variable and it accessed the global variable. What am I missing here?

OpenStudy (anonymous):

If you use variable that is declared in an upper scope, you use the innermost one: ############################ x = 'global' def functionA(): x = 'local' print(x) functionA() # prints 'local' print(x) # prints 'global' ############################# If you reference a variable that isn't in the current scope, you look at outer scopes until you find it: ############################# x = 'global' def functionB(): def functionA(): print(x) # can't find x here # can't find x here either functionB() # prints 'global' print(x) # prints 'global' ############################# but if you try to access a variable declared in an inner scope from an outer one, you get an error: ############################# def functionA(): x = 'local' print(x) functionA() # prints 'local' print(x) # NameError: name 'x' is not defined ############################# One solution is to force the variable to be global: ############################# def functionA(): global x x = 'forcefully global' print(x) # prints 'forcefully global' ############################# If possible however, its preferable to just follow python's scoping rules and let it become global naturally: ############################# x = 'naturally global' def functionA(): print(x) functionA() # prints 'naturally global' print(x) # prints 'naturally global' #############################

OpenStudy (e.mccormick):

The ideas of "scope" and "name spaces" are not Python specific. If you learn about the Python versions, it will help you understand the nature of scope and name spaces in other languages as well. What the above posters talked about is what you want to learn because it is a key idea in computer science!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!