Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Letter Game Refinement - Solved it but can't understand how it works

I managed to successfully complete the letter game refinement but I cannot understand how the following if statement works:

    if guess in secret_word:
        good_guesses.append(guess)
        found = True
        for letter in secret_word:
            if letter not in good_guesses:
                found = False
        if found:
            print("You win! The secret word was {}!".format(secret_word))
            done = True

Can someone please explain how this works? It's really frustrating...

1 Answer

if guess in secret_word:
        good_guesses.append(guess)
        found = True
        for letter in secret_word:
            if letter not in good_guesses:
                found = False
        if found:
            print("You win! The secret word was {}!".format(secret_word))
            done = True

Lets see the code.

if guess in secret_word:

For the letter that is being guessed by the user is checked with secret_word. If its in the secret_word then we do the following things.

So the letter is in secret_word... good, lets add it to the collection of letters that are being guessed.

good_guesses.append(guess)

Our next question is, do we have all the letters in the secret_word? And if so, then we have found the secret_word.

Lets consider, that we have guessed all the letters now and that we have the word.

found = True

And if so then we'll check if we have the letters in secret_word.

for letter in secret_word:

Somewhere if we find that the letters that are being guesses is missed than we say we didn't found it yet and we put found as False

            if letter not in good_guesses:
                found = False

if not, then we were right we have all the letters.

if found:
            print("You win! The secret word was {}!".format(secret_word))
            done = True

Hope this helps. and if i missed something then do reply, else: upvote and accept the answer.