views:

165

answers:

1

I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?

import sys
import codecs
import random

if __name__ == '__main__':
    try:
        wordlist = codecs.open("words.txt", "r")
    except Exception as ex:
        print (ex)
        print ("\n**Could not open file!**\n")
        sys.exit(0)

    rand = int(random.random()*5 + 1)
    i = 0

    for word in wordlist:
        i+=1
        if i == rand:
            print (word, end = '')
            break

    wordlist.close()

    guess = input("Guess a letter: ")
    print (guess) #for testing purposes

    for letters in word:
        if guess == letters:
            print ("Yessssh")

#guessing part and user interface here
+8  A: 

In your "for word in wordlist" loop, each word will end in a newline. Try adding word = word.strip() as the next line.

By the way your last loop could be replaced with:

if guess in word:
    print ("Yessssh")

Bonus tip: when adding "debug prints", it's often a good idea to use repr (especially when dealing with strings). For example, your line:

print (guess) #for testing purposes

Might be more useful if you wrote:

print (repr(guess)) #for testing purposes

That way if there are weird characters in guess, you'll see them more easily in your debug output.

Laurence Gonsalves
Thanks, that repr() command will come in handy
Justen