Python - Variables
Local Variables:
# Local variables are defined within a specific function or block
def my_function():
local_variable = 10
print("Inside function:", local_variable)
# Calling the function to demonstrate the local variable
my_function()
# Attempting to access local_variable here would result in an error
In the above example, the variable local_variable
is defined within the function my_function()
. It is accessible only within the scope of that function. Once the function execution is complete, the local variable is destroyed, and attempting to access it outside the function would result in an error.
Global Variables:
# Global variables are defined outside of any function or block,
# making them accessible throughout the program
global_variable = 20
# Function accessing the global variable
def my_function():
print("Inside function:", global_variable)
# Calling the function to demonstrate the global variable
my_function()
# Global variables are also accessible outside functions
print("Outside function:", global_variable)
In the second example, the variable global_variable
is defined outside any function or block, making it a global variable. It is accessible throughout the entire program, both within and outside functions. The value of the global variable persists for the entire duration of the program.
These examples illustrate the differences in scope and lifetime between local and global variables in Python.
Variable scope in Python refers to the region of the code where a variable is accessible or can be modified. In Python, there are two main types of variable scope: local
and global
.
Local scope
refers to the portion of code where a variable is declared within a function or block. Local variables are only accessible within that specific function or block and are not visible outside of it.
Global scope
refers to the portion of code where a variable is declared outside of any function or block. Global variables are accessible from any part of the code, both inside and outside functions.
# Global variable
global_variable = 10
def example_function():
# Local variable
local_variable = 5
# Accessing global variable within the function
global_variable_inside_function = global_variable + 2
# Printing local and modified global variables
print("Local variable inside function:", local_variable)
print("Modified global variable inside function:", global_variable_inside_function)
# Call the function
example_function()
# Attempting to access local variable outside the function (will result in an error)
# print("Attempt to access local variable outside function:", local_variable)