我有一个问题,以下代码。当我输入确切的秘密字字符时,下面的代码将与密码不匹配。
#initiate words for guessing secretWords =['cat','mouse','donkey','ant','lion']
#Generate a random word to be guessed generateWord = (random.choice(secretWords))
# User have attempts only to the random generate words LeftCount = 6
generateWord = ["_"] * len(secretWords) userInput="" LetterNumber=0 RightGuess =0
while (LeftCount !=0):
print ("Word Contains", len(generateWord),"letters")
print ("You have", str(LeftCount),"attempts remaining")
print ("\n")
print(generateWord)
print ("\n")
userInput=input("Enter word: ")
while(LetterNumber< len(generateWord)):
if(generateWord[LetterNumber] == userInput):
generateWord[LetterNumber]= userInput
RightGuess +=1
LetterNumber +=1
LeftCount -=1
LetterNumber=0
if (RightGuess == len(generateWord)):
print ("Congratulations")
break
if(LeftCount ==0):
print ("Game over")
您正在重写所选单词。
generateWord
同时是密文,也是用户输入。这不行。其他问题我也要纠正:为什么要将generateWord中的一个字母与整个userInput进行比较?在
该行将“LetterNumber”索引处的字符与userInput进行比较,因此如果用户输入一个单词,它将永远不会返回true。在
如果你想计算用户猜测中正确字母的数量,你不应该将用户输入的每个字母与“generateWord”中对应的字母进行比较吗。在
^{pr2}$还有一些一般性的观点,变量名不应该以大写字母开头,根据Python标准,它应该是“字母号码”。试着改进你的变量名,也许叫它“生成的单词”,而不是“生成单词”Generate_word“意味着它是一个函数,因为Generate是一个动词。在
if语句后面的行也将整个userInput重新分配到字母索引处的generateWord值中,为什么要这样做?在
最后,您需要在while循环的末尾或开始处生成一个新词,因为现在您只在开头生成一个词,然后它将在每次迭代中使用相同的词。在
尝试使用print打印出一些变量,这将有助于调试程序,因为它肯定没有达到预期效果。
相关问题 更多 >
编程相关推荐