- #1
fog37
- 1,569
- 108
- TL;DR Summary
- How to correctly use the "global" keyword in Python
Hello,
I am learning about functions and namespaces and I have a question about the keyword global.
Variables defined inside a function are local variables and cannot be used outside of the function by the rest of the program (by using the return keyword, we can assign the value of a local variable to an external variable which is a global variable).
Global variables are defined inside the main program and outside of functions. However, they can be used everywhere in the program, even by the functions. So what is the global for? I think the keyword global is used in the case when a local variable and a global variable have the same name and we want to use/change the specific external global variable directly inside the function itself...
If external and internal variables to a functions have different names, the problem does not arise and there is no need to use global...
Is that correct?
Thank you!
I am learning about functions and namespaces and I have a question about the keyword global.
Variables defined inside a function are local variables and cannot be used outside of the function by the rest of the program (by using the return keyword, we can assign the value of a local variable to an external variable which is a global variable).
Global variables are defined inside the main program and outside of functions. However, they can be used everywhere in the program, even by the functions. So what is the global for? I think the keyword global is used in the case when a local variable and a global variable have the same name and we want to use/change the specific external global variable directly inside the function itself...
If external and internal variables to a functions have different names, the problem does not arise and there is no need to use global...
Is that correct?
Thank you!