我为一个数字猜谜游戏编写代码,它必须通过递归出售。但是当我执行它时,我得到了这个错误:超出了最大递归深度。这是为什么?
这是我的代码:
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)
答案 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 > n
,guess < 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)
random.randint()
这样的功能:n = random.randint(0, 100)
。while
循环。guess = int(input("Introduce a number: "))
。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)