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
我收到此错误:
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
它只是没有正常工作。有人能指出我正确的方向吗?
答案 0 :(得分:1)
问题是letter是一个字符串,hiddenWord期望一个整数索引。要解决此问题,您需要在修改hiddenWord时使用该字母的索引。一个简单的方法是使用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