我试图创建一个简单的代码猜测游戏,用户可以选择随机生成的代码的最小和最大数量。用户必须尝试并猜测代码才能获胜。当我运行我的代码时,get_range()函数工作,然后它继续执行get_guess()函数。但是,当用户输入他/她的输入进行猜测时,代码循环回到get_range()函数的开头。请问有人能帮忙吗?提前谢谢。代码:
import random
import string
print("Welcome to Code Crunchers!")
def get_range():
Min = str(input("Enter the minimum number that the code can be: "))
Max = str(input("Enter the maximum number that the code can be: "))
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min != True or Check_Max != True:
print("Input must only contain integers!")
get_range()
elif Min == Max:
print("Minimum and maximum number must not be equivalent!")
get_range()
elif Min > Max:
print("Maximum number must be greater than minimum number!")
get_range()
else:
Random_Number = random.randrange(int(Min), int(Max))
get_guess()
return Random_Number
def get_guess():
Guess = str(input("Enter your guess: "))
Check_Guess = Guess.isdigit()
if Check_Guess != True:
print("Input must only contain integers!")
get_guess()
else:
validate()
return Guess
def validate():
Random_Number = get_range()
Tries = locals()
Guess = get_guess()
Length = len(str(Random_Number))
Digits_Correct = 0
if Guess == Random_Number:
print("Well done! You guessed the number in", Tries, " tries!")
else:
Digits = ["?"] * Length
Tries += 1
for i in range(0, int(Length)):
if Guess[i] == Random_Number[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("Not quite! You got", Digits_Correct, " digits correct.")
print(Digits)
get_guess()
elif Digits_Correct == 0:
print("None of your digits match!")
get_guess()
def play_again():
Choice = input("Do you want to play again (y/n)?")
if Choice != "y" or Choice != "n" or Choice != "Y" or Choice != "N":
print("Please choose a valid option!")
play_again()
elif Choice == "y" or Choice == "Y":
get_range()
elif Choice == "n" or Choice == "N":
exit()
get_range()
请看下面的代码:
假设您在
get_guess
并且到达else
关闭点,那么您调用validate
。下面是发生的情况:get_guess
调用validate
validate
立即调用get_range
get_range
调用get_guess
get_guess
,请参见(1)因此,您的代码进入无限间接递归
请注意,它在
validate
中永远不会通过Random_Number = get_range()
,您在get_range
和validate
中都调用了get_guess
因此,在将随机数返回到
Random_Number = get_range()
之前,get_range
将尝试get_guess
并立即丢弃其返回值(这就是get_guess()
的作用)。假设get_range
最终返回。现在您将再次调用Guess = get_guess()
,从而要求用户猜两次。我认为这里有一个逻辑缺陷因为您正在
validate()
中调用get_range()
:您可以通过以下方法解决此问题:
但总的来说,这将取决于代码的方向。希望有帮助
相关问题 更多 >
编程相关推荐