A global variable is a variable defined outside any function or class, making it accessible throughout the program, including inside functions and other code blocks. Global variables belong to the program’s global scope, meaning their values can be used anywhere in the same module.
Declaring and Accessing Global Variables
You create a global variable by simply defining it at the top level of your script (outside of functions).
In this example, the function display() can access the global variable x even though it was defined outside the function.
Local vs Global Scope
Python resolves variable names using a rule called scope.
-
Global scope: Variables defined outside functions, accessible anywhere in the module.
-
Local scope: Variables defined inside a function and accessible only within that function.
Here, x inside the function is local and does not modify the global x.
Modifying Global Variables Inside Functions
If you need to change a global variable inside a function, you must declare it using the global keyword. Otherwise, Python treats assignments as creating a new local variable.
The global keyword tells Python to use the global variable count instead of creating a new one inside the function.
Global Variables Created Inside Functions
You can also declare a global variable from within a function by using the global keyword before assignment.
This defines new_var at the global scope, even though the statement appears inside a function.
Best Practices and Cautions
-
Use sparingly: Although convenient, global variables can make code harder to understand and debug because changes in one function can affect behavior elsewhere.
-
Prefer function parameters and return values: Passing data explicitly to functions makes code more modular and easier to test.
-
Constants as globals: It’s common to use global variables for constants (e.g., configuration values) if they don’t change.