Global vs Local Variables

Carson West

Namespaces and Scope

Global vs Local Variables

Scope: The scope of a variable determines where in your code that variable is accessible.

global_var = 10

def my_function():
  print(global_var)  # Accessing global variable inside a function

my_function()  # Output: 10
print(global_var) # Output: 10
def my_function():
  local_var = 5
  print(local_var)  # Accessing local variable

my_function()  # Output: 5
#print(local_var) # This will cause a NameError because local_var is not accessible here.

Modifying Global Variables within Functions:

To modify a global variable from within a function, you must use the global keyword:

global_var = 10

def modify_global():
  global global_var  # Declare that we are modifying the global variable
  global_var = 20

modify_global()
print(global_var)  # Output: 20

Without the global keyword, a new local variable with the same name would be created.

Potential Issues:

Related Notes: