+ 4
I want to understand globals and locals. I guess it refers to global and local variable but still I am confused.
def bar(): x=1 def foo(): print('x' in globals(), 'x' in locals()) foo() bar() *Also if possible, please give example. Thanks
14 Respostas
+ 9
global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.
+ 6
You can study this tutorial about Python namespaces and variable scope.
https://realpython.com/python-namespaces-scope/#the-globals-function
In my opinion, globals() and locals() may be useful for introspection or debugging purpose, but I cannot really imagine a programming scenario where they are inevitable and cannot be replaced by more sane and clean alternatives.
+ 5
There are plenty of ways to shoot yourself in the foot, if you make a function change something that is outside of its scope. You may not feel the pain with 4-5 lines of code, but if you have hundreds of lines and you are trying to figure out what went wrong, you could be banging your head in the wall for hours.
Python gives you a lot of power, and as the saying goes, with great power comes great responsibility. You can avoid many pitfalls by NOT using globals at all, and not passing mutable data to functions.
+ 4
Tibor Santa t thanks
+ 4
Thanks buddy, you all are fabulous. Helping me/sololearners so promptly. Unable to mention it in words. Great.
Thanks Rđžđźđł
Thanks Jay Matthews
+ 4
It is not mandatory to use globals and locals, in fact I said exactly the opposite.
"I CANNOT imagine" a situation where I would use them instead of something else.
+ 3
Sakshi thanks
+ 3
Tibor Santa sorry sir, I misunderstood you. Got your point. Thanks
+ 2
Tibor Santa please elaborate "the mandatory use/disuse" of globals and locals.
"Locals and global s are inevitable and cannot be replaced by more sane and clean alternatives."
+ 2
Let consider a programme/code where there is a global x (type==int). And you want to change its value through function. How will you do it without using global?
Never mind, I think it's not possible without using global keyword
+ 2
As others have stated, it is best not to mess with globals and locals in serious production code, because it might produce hard to debug side effects.
But if you are just playing, you can do this:
https://code.sololearn.com/c5zsFr9C8UCI/?ref=app
+ 1
Global variables are that variables which can be accessible and also changeable from the entire code and if we talk about local then they only can be accessible and changeable from it's declaration scope , that means the part of in which they are declared.
0
Int main()
{
Int k;
// k variable is global variable can be accessed globally entire program.
For(int i =0 ; i<5; i++;)
{
// i variable is local variable it can be accessed in only for loop body
}
Return 0;
}