Describe the difference between global and local variables in Python
Global vs Local Variables in Python: Understanding the Difference
Python variables are classified into two main types based on their scope: global variables and local variables.
Global variables:
- Global variables are declared outside of any function or at the top level of a script.
- Their global scope makes them accessible throughout the program.
- A program's global variables are created when it starts and remain in memory until the program ends.
- Any function within the program can access and modify global variables.
Example: Global variable
global_var1 = 250 # This is a global variable
def function_with_global_var():
print("Global variable value:", global_var1)
function_with_global_var() # Output: Global variable value: 250
Local variables:
A local variable is one that is declared within a function and has a local scope.
- They are accessible only within the function in which they are defined.
- Local variables are created when the function is called and destroyed when it exits.
- Local variables cannot be accessed from outside the function.
Example: Local variable:
def function_with_local_var():
local_var = 45 # This is a local variable
print("Local variable value:", local_var)
function_with_local_var() # Output: Local variable value: 45
print(local_var) # Error: NameError - local_var is not defined
Using global variables inside a function:
It is necessary to use the global keyword before the variable name if you want to use a global variable inside a function. This allows you to modify the global variable within the function.
Example: Using a global variable inside a function
global_var = 400
def function_with_global_var():
global global_var
global_var += 50
function_with_global_var()
print(global_var) # Output: 450
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/describe-the-difference-between-global-and-local-variables-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics