简体   繁体   English

列出索引while循环python

[英]List index while loop python

I have an issue with the following code.我有以下代码的问题。 When i typed the exact secret words character, the following code wont match the secret codes.当我输入确切的密码字符时,以下代码与密码不匹配。

#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")

Why are you comparing one letter in generateWord to the entire userInput?为什么要将 generateWord 中的一个字母与整个 userInput 进行比较?

if(generateWord[LetterNumber] == userInput):

That line compares the character at "LetterNumber" index to the userInput, so if a user enters a word it will never return true.该行将“LetterNumber”索引处的字符与 userInput 进行比较,因此如果用户输入一个单词,它将永远不会返回 true。

If you're attempting to count the number of correct letters in the users guess, shouldn't you be comparing each letter from the user input with the corresponding letter in the "generateWord".如果您试图计算用户猜测中正确字母的数量,您不应该将用户输入中的每个字母与“generateWord”中的相应字母进行比较。

if(generateWord[LetterNumber] == userInput[LetterNumber]):

Also some general points, variable names shouldn't start with a capital, it should be "letter_number" according to Python standards.还有一些一般性的观点,变量名不应该以大写开头,根据 Python 标准应该是“letter_number”。 Try to improve your variable names as well, maybe call it "generated_word", not "generate_word".尝试改进您的变量名称,也许称之为“generated_word”,而不是“generate_word”。 "Generate_word" implies it is a function, as generate is a verb. “Generate_word”暗示它是一个函数,因为 generate 是一个动词。

The line after the if statement also reassigns the entire userInput into the generateWord value, at the letter index, why are you doing that? if 语句之后的那一行也将整个 userInput 重新分配到 generateWord 值中,在字母索引处,你为什么要这样做?

Finally, you need to generate a new word at the end of your while loop, or maybe the beginning, as at the moment you only generate a word at the beginning, then it will use the same word in each iteration.最后,您需要在 while 循环的结尾或开头生成一个新单词,因为此时您只在开头生成一个单词,然后它将在每次迭代中使用相同的单词。

Try to use print to print out some of your variables, it will help you debug your program, as it's definitely not doing what you expect.尝试使用 print 打印出您的一些变量,它会帮助您调试程序,因为它绝对不是您期望的那样。

You are overriding your selected word.您正在覆盖您选择的单词。 generateWord is at the same time the secret word, and the user input. generateWord同时是秘密词,也是用户输入。 This can't work.这是行不通的。 Here is something that should do what you want (I also corrected some other problems):这是应该做你想做的事情(我还纠正了一些其他问题):

import random

secretWords = ["cat", "mouse", "donkey", "ant", "lion"]

generatedWord = random.choice(secretWords)
leftCount = 6
userWord = ["_"] * len(generatedWord)
refusedLetters = ""

#returns all positions of character ch in the string s
def findOccurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

print("Word contains", len(generatedWord), "letters")
while(leftCount > 0 and generatedWord != "".join(userWord)):
    print ("\n")
    print ("You have", str(leftCount), "attempts remaining")
    print ("Letters not present in your word:", "".join(sorted(refusedLetters)))
    print ("Your word so far: ","".join(userWord))
    print ("\n")

    #checks that the user enters something
    userInput = ""
    while not len(userInput):
        userInput=input("Enter letter or word: ")
    userInput = userInput.lower()

    #if len > 1, then the user has tried to guess the whole word:
    if len(userInput) > 1:
        if generatedWord == userInput:
            print("Congratulations")
            break
        else:
            print("Wrong word, sorry")
    #len == 1, thus the user asked for one letter
    else:
        #if letter isn't already found
        if not userInput in userWord:
            #for all occurences of the letter in the secret word
            occurences = findOccurences(generatedWord, userInput)
            for occurence in occurences:
                userWord[occurence] = userInput
            #if the letter was not found
            if not occurences:
                #if the letter has already been proposed
                if userInput in refusedLetters:
                    print("You have already tried this letter")
                    continue
                else:
                    refusedLetters += userInput
        else:
            print("You have already tried this letter")
            continue

    leftCount -= 1

#the else statement will only be entered if we did not exit the previous loop via a break.
#Thus, if the word has already been found, nothing happens here.
else:
    if generatedWord == "".join(userWord):
        print("Congratulations")
    else:
        print("Game over")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM