can someone please explain to me the concept of a namespace in python programming language
thanks a lot guys!! :)
explain why this code gives an error : def printxAndSetxTo9() : print(x) x = 9 x = 35 printxAndSetxTo9()
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)
oh i forgot,explain in terms of namespaces why it gives an error
i don't know what namespaces are :D
ok,thanks anyway!
The local 'x' identifier being referenced inside the function printxAndSetxTo9() is different from the x defined at the global scope ('x = 35')
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
or you can do it Tomas.A's way and not have to worry about scoping and namespaces.
Join our real-time social learning platform and learn together with your friends!