为什么我的Python方法在调用return语句后继续?

为什么我的Python方法在调用return语句后继续?,python,recursion,Python,Recursion,当执行以下方法时,它将正确运行,直到到达返回路径的第一个return语句。此时,它不会退出该方法,而是跳到倒数第二行,然后再次调用该方法,从而导致无限递归。调用return后,该方法不应该自动退出吗 def main(): if len(sys.argv) > 2: sys.exit("Usage: python degrees.py [directory]") directory = sys.argv[1] if len(sys.argv) == 2 el

当执行以下方法时,它将正确运行,直到到达返回路径的第一个return语句。此时,它不会退出该方法,而是跳到倒数第二行,然后再次调用该方法,从而导致无限递归。调用return后,该方法不应该自动退出吗

def main():
    if len(sys.argv) > 2:
        sys.exit("Usage: python degrees.py [directory]")
    directory = sys.argv[1] if len(sys.argv) == 2 else "small"

    # Load data from files into memory
    print("Loading data...")
    load_data(directory)
    print("Data loaded.")

    source = person_id_for_name(input("Name: "))
    if source is None:
        sys.exit("Person not found.")
    target = person_id_for_name(input("Name: "))
    if target is None:
        sys.exit("Person not found.")

    path = shortest_path(source, source, target, set(), list())

    if path is None:
        print("Not connected.")
    else:
        degrees = len(path)
        print(f"{degrees} degrees of separation.")
        path = [(None, source)] + path
        print(path)


def shortest_path(original, source, target, visitedpeople=set(), path=list()):
    """
    Returns the shortest list of person_id
    that connect the source to the target.

    If no possible path, returns None.
    """
    if source == target:
        return []
    while source != target:
        destinations = neighbors_for_person(source)
        visitedpeople.add(source)
        neighbors = list()
        for x in range(len(destinations)):
            neighbors.append(destinations[x])
        if neighbors.__contains__(target):
            for neighbor in destinations:
                if neighbor == target:
                    path.append(neighbor)
            return path
        else:
            if all(x in visitedpeople for x in neighbors):
                shortest_path(original, original, target, visitedpeople, path)
            else:
                for neighbor in destinations:
                    if neighbor not in visitedpeople:
                        path.append(neighbor)
                        visitedpeople.add(neighbor)
                        shortest_path(original, neighbor, target, visitedpeople, path)
    return []


您能添加调用此函数的代码吗?函数到达返回时将始终退出。一定还有别的事。您可能看到前一个递归调用结束,因为您没有返回递归调用的结果。我认为您有一个错误的想法,即当递归函数返回时,它也会导致原始调用返回。事实并非如此。我有,这可能有助于您理解一些简单示例中发生的情况-当递归调用返回时,它返回的值进入调用堆栈中它上面的调用,然后该调用继续。不要将可变值作为默认参数。我不认为这是您所看到的问题,但是在对默认参数的后续调用中,列表和set-as参数被重用。见: