kamcho 56 kamcho 56 - 22 days ago 7
Python Question

Python claims my list does not have the char i am looking for

I'm trying to make a hangman game. I'm doing little bits at a time as I'm still figuring many things out.

This problem really has me stuck here. I trying to print a character which is in my list of "guesses" so long as the character I'm comparing it with is in the list.

But for some reason it seems to think that the character isn't in the list. Even when I hard code the value it still doesn't work.

def win(guesses):
if guesses == lst:
return True
else:
return False


def check(guess):
fail = 0
#char = str(guess)
for char in lst:
if char in guess:
guesses.append(guess)
return True
else:
fail = fail + 1
if fail == len(lst):
return False
#Start up!
word = "jamie"
lst = []
Guess = ''
guesses = []
for c in word:
lst.append(c)
for char in word:
print '_',
# Lets play!
won = False
while won == False:
Guess = raw_input("\nGuess a letter: "),
while Guess in guesses:
Guess = raw_input("\nPlease choose a letter not already used: "),
ans = check(Guess)
if ans == True:
for c in lst:
if c in guesses:
print c,
else:
print "_",
won = win(guesses)
else:
print "Great job you won!"
print guesses


P.S

I apologize if it's hard to read but if there are any tips or more sensible ways to improve my code I'm happy to hear them.

Answer

You are getting unexpected results due to a single character:

Guess = raw_input("\nGuess a letter: "),
                                       ^

Adding a comma like this produces a tuple that contains a single element of the string you're interested in.

>>> x = 1
>>> x
1
>>> type(x)
<class 'int'>
>>> x = 1,
>>> x
(1,)
>>> type(x)
<class 'tuple'>

Don't add a comma after either raw_input call. It does not work the same way as the print statement.