此问题在此处已有答案:
How can I read inputs as numbers?(10个答案)
两年前关闭了。
我正在尝试做一个代码猜谜游戏,用户可以选择代码的范围,用户尝试猜随机生成的代码,直到猜对为止,计算机还会显示用户猜对了哪些数字,问题是当用户确实猜对了代码这个过程只是停止,即使我的代码说打印一个祝贺消息,并再次播放功能。请任何人都可以帮助?谢谢。代码:
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
elif Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if Guess == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[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(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
Choice = input("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()
2条答案
按热度按时间vcirk6k61#
我认为这里的问题是你的
Guess
是一个字符串,而你的Random
是一个整数。要解决这个问题,你可以尝试将Guess
转换为整数或将Random
转换为字符串。试试这个:h6my8fg22#
我认为你的问题是
str
和int
类型。首先,你的Min
和Max
是字符串,所以你的行:elif Min > Max: print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
不能正常工作。另一个问题是你的变量Guess
和Random
是不同的类型,所以Guess == Random
总是会返回False
。下面是正确的代码版本。
我还添加了一些
if
案例,以便能够在不关闭程序的情况下退出程序。