Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python递归函数不正确地执行return语句?_Python_Recursion_Return Value - Fatal编程技术网

Python递归函数不正确地执行return语句?

Python递归函数不正确地执行return语句?,python,recursion,return-value,Python,Recursion,Return Value,我正在做一个简单的游戏,其中包括两名玩家。每个玩家都有两个计数器,可以通过选择它们来单独移动。玩家1有计数器1和1,而玩家2有计数器3和4。为了防止玩家移动对手的一个计数器,我编写了以下递归函数 如果没有人“作弊”,那就没问题了 如果玩家作弊,函数会让他们重新输入正确的计数器编号。这将按预期执行到最终返回语句 然而,在这一点上,它似乎没有返回正确的计数器编号,而是采取了另一个步骤,将其更改为初始错误值。这就好像代码已经记住了在递归过程中尝试过的变量计数器的所有值,并在返回第一个值之前循环它们 我

我正在做一个简单的游戏,其中包括两名玩家。每个玩家都有两个计数器,可以通过选择它们来单独移动。玩家1有计数器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

您以递归方式调用函数,但不返回递归结果。添加
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
语句。局部
计数器
变量在递归函数调用之间不共享,因此它是玩家做出的最终从最外层调用返回的第一个选择

但是,不要低估用户继续尝试和欺骗的能力;最终将进入最大递归深度。您不应该真正使用递归来处理用户输入;改为使用循环:

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
仅当输入了正确的计数时才返回;如果输入错误,则继续循环(重新屏蔽问题)