1
import random

words = ["antelope", "attacking", "architect", "defector", "mindless", "trauma", "immunity", 
    "fairytale", "approaching", "cuteness", "identical", "caterpillar"]

lives = 6
word = random.choice(words)
guessedWord = False

print "Welcome to Hangman. You have 6 lives, good luck!"
hiddenWord = "_ " * len(word)
print hiddenWord

while True:
    if lives == 0 and not guessedWord == True:
        break

    guess = raw_input("Guess A Letter: ")

    if len(guess) > 1:
        print "Please only guess letters."
    else:
        if guess.isdigit() == True:
        print "Please only guess letters."
        else:
            for letter in word:
                if guess == letter:
                    hiddenWord[letter] == letter
                    print "Nice, You got a letter!"
                    print hiddenWord
                else:
                    "That letter is not in this word. -1 life."
                    lives = lives - 1

I get this error:

Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Users\Brian Gunsel\Desktop\Code\Python\hangman.py", line 28, in <module>
    hiddenWord[letter] == letter
TypeError: string indices must be integers, not str

And it just isn't working properly. Can someone point me in the right direction?

Andy
  • 49,085
  • 60
  • 166
  • 233
Brian Gunsel
  • 111
  • 2
  • 9

1 Answers1

1

The problem is that letter is a string, and hiddenWord is expecting an integer index. To fix this, you want to use the index of that letter when modifying hiddenWord. An easy way to do this is with enumerate().

for i, letter in enumerate(word):
    if guess == letter:
        hiddenWord = hiddenWord[:i] + letter + hiddenWord[i+1:]
        print "Nice, You got a letter!"
        print hiddenWord
    else:
        "That letter is not in this word. -1 life."
        lives = lives - 1
pzp
  • 6,249
  • 1
  • 26
  • 38
  • This won't work exactly as-is because strings are immutable in Python; see https://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python – mpontillo Feb 16 '16 at 03:36
  • 1
    @Mike I realized right after I pushed submit. Fixed now. – pzp Feb 16 '16 at 03:38