Search code examples
pythonfunctionreturn-value

Python return statement not returning correct output


I have a simple function to return True or False when a condition is met. But the return statement is not functioning as I expected. Could anyone help me out to point out the mistake I am making.

graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'j': ['i'],
'k': []
}

def hasPath(graph,source,des):
    arr = graph[source]
    if des in arr:
        print('Yes')
        return True
    for i in arr:
        hasPath(graph,i,des)
    return False

print(hasPath(graph,'f','k'))

This code return False but prints the statment Yes. I am not sure why return statement is not being executed after the Print statement.


Solution

  • In the hasPath function, you are calling the function recursively on each element in the arr list, and the return value of the recursive calls is not being used. This means that even if the des value is present in the arr list and the print statement is executed, the return False statement at the end of the function will still be executed and the False value will be returned.

    To fix this issue, you can add a return statement after the recursive call to hasPath to return the value of the recursive call. This will ensure that the return True statement is executed when the des value is found in the arr list, and the return False statement at the end of the function will not be executed.

    Here is an example of how you can modify the hasPath function to fix this issue:

    def hasPath(graph, source, des):
        arr = graph[source]
        if des in arr:
            print('Yes')
            return True
        for i in arr:
            if hasPath(graph, i, des):
                return True
        return False
    

    With this change, the hasPath function will return True when the des value is found in the arr list, and will return False otherwise. When you run the print(hasPath(graph, 'f', 'k')) statement, it will print Yes and then True, as expected.