简体   繁体   中英

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?

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.

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".

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. Try to improve your variable names as well, maybe call it "generated_word", not "generate_word". "Generate_word" implies it is a function, as generate is a verb.

The line after the if statement also reassigns the entire userInput into the generateWord value, at the letter index, why are you doing that?

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.

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.

You are overriding your selected word. generateWord is at the same time the secret word, and the user input. 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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