Global Variables
Global Variables
These are variables that are created outside of a function are known as global variables and have a
global scope.
Accessibility: Global variables are accessible throughout the program and inside every function.
Scope: Global variables have a global scope, meaning they can be accessed from any part of the
program.
Lifetime: Global variables have a lifetime which exists for the duration of the program’s execution.
1. Convenience : Global variables can be accessed from anywhere in the program, making it easier to
share data between functions.
2. Efficiency: global variables can reduce the need for function arguments and return values, making the
code more efficient.
1. Namespace pollution: global variables can clutter the global namespace , making it harder to
find and use variables.
2. Code complexity: global variables can make the code harder to understand and maintain, as
their values can be changed from anywhere in the program.
1. Use sparingly: Use global variables only where , and prefer loval variables or function instead
arguments instead.
2. Use meaningful names : Use descriptive and meaningful names for global variables to avoid
confusion.
3. Avoid mutable global variables as they can lead to thread safety issues and code complexity.
4. Use encapsulation: Encapsulate global variables within a namespace or a class to avoid
namespace pollution.
Example
print(“inside function”, s )
s= “I love you”
f()
print(“outside function”, s )
If you create a variable with the same name inside a function, this variable will be local, and can only be
used inside the function. The global variable with the same name will remain as it was, global and with
the original value.