Python递归函数返回语句执行不正确?

1 投票
1 回答
1329 浏览
提问于 2025-04-18 05:50

我正在做一个简单的游戏,里面有两个玩家。每个玩家都有两个棋子,可以单独移动,玩家1有两个棋子,都是1,玩家2有棋子3和4。为了防止一个玩家移动对方的棋子,我写了一个递归函数。

这个函数在没有人“作弊”的情况下运行得很好。

如果有玩家作弊,函数会让他们重新输入一个正确的棋子编号。这一过程会一直传递到最后的返回语句,结果是符合预期的。

但是在这个时候,函数并没有返回一个正确的棋子编号,反而似乎又多走了一步,把它改回了最初的错误值。就好像代码记住了在递归过程中尝试过的所有棋子编号,并在最后返回了第一个尝试的那个。

我漏掉了什么呢?

def get_counter(current_player):
    counter = int(input("Select which counter you want to move."))
    if counter != 1 and counter != 2 and current_player == 1:
        print("This is not your counter")
        print("Your counters are 1 or 2")
        get_counter(current_player)
    elif counter != 3 and counter != 4 and current_player == 2:
        print("This is not your counter")
        print("Your counters are 3 or 4")
        get_counter(current_player)
    return counter

1 个回答

3

你在调用这个函数的时候用了递归,但没有返回递归的结果。你需要加上 return 语句:

def get_counter(current_player):
    counter = int(input("Select which counter you want to move."))
    if counter != 1 and counter != 2 and current_player == 1:
        print("This is not your counter")
        print("Your counters are 1 or 2")
        return get_counter(current_player)
    elif counter != 3 and counter != 4 and current_player == 2:
        print("This is not your counter")
        print("Your counters are 3 or 4")
        return get_counter(current_player)
    return counter

如果不明确返回递归调用 get_counter() 的结果,调用这个函数的地方会继续执行之前的代码,然后执行 return counter 语句。每次递归调用时,局部的 counter 变量是独立的,所以最终返回的结果是玩家第一次选择的那个。

不过,别小看用户的能力,他们可能会继续尝试作弊;最终你会遇到递归的最大深度限制。处理用户输入时其实不应该用递归,应该用循环来代替:

def get_counter(current_player):
    while True:
        counter = int(input("Select which counter you want to move."))
        if current_player == 1 and counter not in (1, 2):
            print("This is not your counter")
            print("Your counters are 1 or 2")
            continue
        if current_player == 2 and counter not in (3, 4):
            print("This is not your counter")
            print("Your counters are 3 or 4")
            continue
        return counter

这样只有在输入正确的计数时才会返回;如果输入错误,就会继续循环(重新问问题)。

撰写回答