4 5 2 Global Variables Explained
Key Concepts
Global variables in Python are variables that are defined outside of any function or block. They can be accessed from any part of the program, including inside functions. The key concepts include:
- Definition of Global Variables
- Scope of Global Variables
- Modifying Global Variables Inside Functions
- Global Keyword
1. Definition of Global Variables
A global variable is defined at the top level of a Python script or module. It is not nested inside any function or class. Global variables are accessible throughout the entire program.
Example:
global_var = 10 # This is a global variable def my_function(): print(global_var) # Accessing the global variable my_function() # Output: 10
2. Scope of Global Variables
The scope of a global variable is the entire program. This means that any function or block can access and use the global variable without needing to pass it as an argument.
Example:
global_var = 10 def my_function(): print(global_var) # Accessing the global variable def another_function(): print(global_var) # Accessing the global variable my_function() # Output: 10 another_function() # Output: 10
3. Modifying Global Variables Inside Functions
If you want to modify a global variable inside a function, you need to use the global
keyword. This tells Python that you are referring to the global variable, not creating a new local variable with the same name.
Example:
global_var = 10 def modify_global(): global global_var # Declare that we are using the global variable global_var = 20 # Modify the global variable modify_global() print(global_var) # Output: 20
4. Global Keyword
The global
keyword is used inside a function to indicate that a variable is a global variable. This is necessary if you want to modify the global variable inside the function.
Example:
global_var = 10 def modify_global(): global global_var # Use the global keyword global_var = 20 # Modify the global variable modify_global() print(global_var) # Output: 20
Putting It All Together
By understanding and using global variables effectively, you can create variables that are accessible throughout your entire program. This can be useful for constants or variables that need to be shared across multiple functions.
Example:
global_var = 10 def increment_global(): global global_var global_var += 1 def print_global(): print(global_var) increment_global() print_global() # Output: 11 increment_global() print_global() # Output: 12