Exception has occurred: UnboundLocalError local variable 'depth' referenced before assignment

shivajikobardan

Junior Member
Joined
Nov 1, 2021
Messages
107
This code is for iterative deepening depth first search in python.

Code:
# Python dictionary to act as an adjacency list
graph = {
  '7' : ['19','21', '14'],
  '19': ['1', '12', '31'],
  '21': [],
  '14': ['23', '6'],
  '1' : [],
  '12': [],
  '31': [],
  '23': [],
  '6' : []
}
visited=[]
goal='31'
depth=0

depth_limit=2
def dls(visited, graph, node,depth_limit):
    if(node==goal):
            print("goal found")
            return True

    
    if(depth>=0):
        #to print path
        if node not in visited:
            visited.append(node)
        
        

        for neighbor in graph[node]:
            dls(visited, graph, neighbor,depth_limit-1)
        

    return False


def iddfs(visited,graph,node):
    while True:
        solution=dls(visited,graph,node,depth_limit)
        if(solution==goal):
            print("Success goal find at depth=",depth)
            print("Path=",visited)     
        depth=depth+1
 
        

print("Following is the Depth-First Search")
iddfs(visited, graph, '7')

There are various pseudocodes available for this problem. They are as follows-:
I did my best to understand and implement the code but I seem to have failed. And it is getting really confusing. Can you help me?


 
You need to add a "global" declaration to the "iddfs" function, but when I did that the code went into infinite loop after awhile.

Code:
def iddfs(visited,graph,node):
    global depth;
    while True:
     ....
 
An UnboundLocalError is raised when a local variable is referenced before it has been assigned. In most cases this will occur when trying to modify a local variable before it is actually assigned within the local scope. Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword). A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment. UnboundLocalError happend because when python sees an assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function. However, to modify a global variable inside a function, you must use the global keyword.
 
Top