为什么我不断超出最大递归深度错误?

时间:2015-10-11 23:23:41

标签: python recursion

我为一个数字猜谜游戏编写代码,它必须通过递归出售。但是当我执行它时,我得到了这个错误:超出了最大递归深度。这是为什么?

这是我的代码:

import random
n = random.randrange(0,100)
guess = int(input("Introduce a number: "))
def game(guess):
    if guess == n:
        print("Your guess is correct.")
    elif guess > n:
        print("Your guess is too high")
        game(guess)
    elif guess < n:
        print("Your guess is too low")
        game(guess)
game(guess)

4 个答案:

答案 0 :(得分:1)

原因是,除非guess在您第一次调用函数时等于n,否则您将获得无限递归,因为您使用相同值{{game调用guess 1}}。您没有提供任何方法来停止递归。

答案 1 :(得分:0)

您的游戏功能不需要任何参数。您需要使用else代替上一个elif并且guess = int(input("Introduce a number: "))步骤应该在您的游戏功能中(已测试):

import random
n = random.randrange(0,100)
def game():
    guess = int(input("Introduce a number: "))
    if guess == n:
        print("Your guess is correct.")
    elif guess > n:
        print("Your guess is too high")
        game()
    else:
        print("Your guess is too low")
        game()
game()

答案 2 :(得分:0)

maximum recursion depth exceeded由于guess > nguess < n条件满足时的无限循环而发生。 要进一步了解this question

以下代码应按预期工作。

import random,sys
n = random.randrange(0,100)

def game(guess):
    if guess == n:
        print("Your guess is correct.")
        sys.exit()
    elif guess > n:
        print("Your guess is too high")
    elif guess < n:
        print("Your guess is too low")

while True:
    guess = int(input("Introduce a number: "))
    game(guess)

答案 3 :(得分:0)

  1. 您需要使用random.randint()这样的功能:n = random.randint(0, 100)
  2. 建议使用while循环。
  3. 您没有再次致电guess = int(input("Introduce a number: "))
  4. import random
    n = random.randint(0, 100)
    guess = int(input("Introduce a number: "))
    
    def game(guess):
        while guess != n:
            if guess > n:
                print("Your guess is too high")
            elif guess < n:
                print("Your guess is too low")
            guess = int(input("Introduce a number: "))
    
        else:
            print("Your guess is correct.")
    
    game(guess)