local variable referenced before assignment python code example

Example 1: python local variable referenced before assignment

variable = "Hello"
def function():
  global variable
  print(variable)
function()

Example 2: unboundlocalerror local variable referenced before assignment python

"""
This happens when python thinks that your variable is local
(the scope is only within a specific function) and/or that
you have not assigned a value to the variable before in this
specific function (scope).

try:
 - assigning the variable a value within the function
 - Passing the variable to the function using it when calling the function
 - Declaring the variable as global (bad practice)
 
Read more about this error in the source
"""

Example 3: python referenced before assignment in function

# When Python parses the body of a function definition and encounters an assignment such as

 feed = 5 
#Python interprets feed as a local variable by default. If you do not wish for it to be a local variable, you must put

global feed
feed = 5