Reputation: 1
I'm writing a hangman game and can't figure out how to account for words of varying lengths, and my code doesn't seem to work.
Here are the steps:
['_','_','_','_','_','_']
word = random.choice(i)
guesses = 0
turns = 11
a = [['_']*len(word)]
print(a)
print ( word)
while turns > 0:
letter = input('Enter a letter:')
for i in range (0, 6):
if word[0][i] == letter:
a[0][i] = letter
print(a)
if a == word:
turns -= 1
print("You won. ")
else :
turns -= 1
Upvotes: 0
Views: 56
Reputation: 9787
You need to loop through the entire length of word
, instead of only 6
letters:
for i in range (0, len(word)):
Don't put a
inside of a list, to get your desired format:
a = ['_']*len(word)
print(a) # ['_','_','_','_','_','_']
In your loop you should just access i
directly
if word[i] == letter:
a[i] = letter
Check that the game is over by joining the list of letters together into a string:
print(''.join(['h', 'i']) # 'hi'
if ''.join(a) == word:
If they won, break
out of the while loop:
print("You won. ")
break
For style, add a space after the input prompt:
letter = input('Enter a letter: ')
Also, remove the guesses
variable if you aren't using it. And don't print(word)
(once you're done debugging).
NOTE: This assumes that word
is a string, not a list of strings. I believe this is a better implementation.
Upvotes: 2
Reputation: 260
I agree with @JBallin , but instead of
for i in range (0, len(word)):
you can use
for index,ch in enumerate(word):
where index is from 0 to length of the word, and ch is the character itself
Upvotes: 0
Reputation: 235
A working example:
word = "dead"
guesses = 0
turns = 11
a = ["_" for i in range(0,len(word))]
print(a)
print (word)
while turns > 0:
letter = input('Enter a letter:')
for i in range (0, len(word)):
if word[i] == letter:
a[i] = letter
print(a)
if "".join(a) == word:
print("You won.")
break
turns -= 1
Upvotes: 1