Today in class my teacher told me that I shouldn't use global variables in python, as the function should be able to exist on its own. I thought I might be able to do this with parameters and returning a value? Any help would be great, thanks.
Asked
Active
Viewed 2,220 times
0
-
2Please, could you provide a minimum example of what you did and what your teacher asked you to change it to? – vvilin Feb 27 '20 at 18:40
-
1Your teacher is correct. Global variables make it harder for a function to operate in multiple contexts. – Barmar Feb 27 '20 at 18:40
-
This question would be more appropriate for [softwareengineering.se]. It's not just on Python, global variables should be avoided in most languages. – Barmar Feb 27 '20 at 18:41
-
Python does not have global variables in the sense that a language with a global context like JavaScript (window.x) has. It's important to scope variables appropriately, but at worst, your variables would be scoped to the module, and effectively namespaced there. – kojiro Feb 27 '20 at 18:44
-
SO is for programming help, so as it is this kind of question doesn't quite fit. Maybe follow vvlin's advice and add an example. In general, you should avoid global variables unless you have a good reason that can't be solved easily without them. – 101arrowz Feb 27 '20 at 18:44
1 Answers
3
Not only in Python, But We should also avoid using global variables in any language. These are some of the reasons why global variables are considered bad −
(1) Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use.
(2) A global variable can have no access control. It can not be limited to some parts of the program.
(3) Using global variables causes very tight coupling of code.
(4) Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value.
(5) Testing in programs using global variables can be a huge pain as it is difficult to decouple them during testing.

Amit Rautray
- 176
- 7