Is it possible to store inputted values in a while loop?

Viewed 42

I'm trying to store the guesses so that I can make code for if you have already guessed that letter and also to make code for when they get all of the letters correct. I may be stuck on that part, too, since I don't know how to check if the letters correspond to the letters in the wordname list, especially when it isn't even ordered.

So, I am looking for some code that would store the guesses and also something that can check if all of the correct letters have been guessed. I am thinking it may have something to do with the enumerate() function, but I am not sure since I have never used it before and have only just heard about it.

Also, for your information, the game is hangman if that helps.

wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)

def letter_guess1():
    sleep(1)
    tries = 5
    print(f"{oppositeplayer}, the word is {wordnamelength} letters long")
    while tries > 0:
        guess1 = input("Make your guess: ")
        if guess1 in wordnamelist:
            print("Congrats, that is correct")
            letternum = wordnamelist.index(guess1)
            letternum += 1
            print(f"This letter is number {letternum}")
        elif guess1 not in wordnamelist:
            tries -= 1
            print(f"You have {tries} left")
        if guess1 == "quit".lower():
            exit()
    return tries

tries = letter_guess1()
1 Answers

I think set is very suitable in this situation. Keep the letters of the word being guessed as a set and add the guess to another set. Then, you can check if the word was guessed correctly by using the intersection of both sets.

Something like that:

wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)

def letter_guess1():
    sleep(1)
    tries = 5
    print(f"{oppositeplayer}, the word is {wordnamelength} letters long")

    word_set = set(wordname)
    guessed_letters = set()
    while tries > 0:
        guess = input("Make your guess: ")
        if guess in guessed_letters:
            print("You already guessed this letter")
            continue

        guessed_letters.add(guess)
        if guess in word_set:
            print("Congrats, that is correct")
            letternum = wordnamelist.index(guess)
            letternum += 1
            print(f"This letter is number {letternum}")
        elif guess not in word_set:
            tries -= 1
            print(f"You have {tries} left")

        if word_set.intersection(guessed_letters) == word_set:
            print("You have won!")

        if guess == "quit".lower():
            exit()
    return tries

tries = letter_guess1()
Related