Ask your own question, for FREE!
Computer Science 14 Online
OpenStudy (anonymous):

can someone please explain to me the concept of a namespace in python programming language

OpenStudy (asnaseer):

this might help you: http://bytebaker.com/2008/07/30/python-namespaces/

OpenStudy (anonymous):

thanks a lot guys!! :)

OpenStudy (anonymous):

explain why this code gives an error : def printxAndSetxTo9() : print(x) x = 9 x = 35 printxAndSetxTo9()

OpenStudy (anonymous):

you inside of function print x which is undefined inside function and you set x to 9 as function variable but you do not return it you should write code like this def printxAndSetxTo9(x): print(x) x = 9 return x x = 35 x = printxAndSetxTo9(x)

OpenStudy (anonymous):

oh i forgot,explain in terms of namespaces why it gives an error

OpenStudy (anonymous):

i don't know what namespaces are :D

OpenStudy (anonymous):

ok,thanks anyway!

OpenStudy (anonymous):

The local 'x' identifier being referenced inside the function printxAndSetxTo9() is different from the x defined at the global scope ('x = 35')

OpenStudy (anonymous):

what you can do is include the following statement at the top of the function, and it will be able to access the global 'x' variable, and modify its value etc. global x So your function should look like this: def printxandsetxto9(): global x print(x) x = 9 now if you do the following: x = 35 printxandsetxto9() print x you will get the following output: >>> 35 >>> 9

OpenStudy (anonymous):

or you can do it Tomas.A's way and not have to worry about scoping and namespaces.

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!