【发布时间】:2012-02-08 02:09:05
【问题描述】:
我在第二年 Comp。我在大学的 Sci 和我最近的作业中遇到了一个问题。我必须制作一个 Hangman 游戏,100% 喜欢他们的输出和规格。我会用数字格式化列表,但我不知道如何,对于 SO 来说是新手。我的问题出现在区块中:
for i in range(0, stringSize, 1):
answerStr[i] = '_'
哪里出错了
int object does not support item assignment
在其他语言中,我可以只制作一个大小为 (userChosenWord) 的字符串,但我在 Python 的字符串库及其动态类型方面遇到了问题。在作业中,我必须将当前字符串输出为_____,如果用户要猜测e 中的单词horse,我必须告诉用户Letters matched so far: ____e。我希望这是有道理的。
另外,如果你们中的任何人对我的代码有提示/cmets,请告诉我。我一直在学习。
wordList = ['cow', 'horse', 'deer', 'elephant', 'lion', 'tiger', 'baboon', 'donkey', 'fox', 'giraffe'] #will work for words <=100 chars
inputList = "abcdefghijklmnopqrstuvwxyz"
illegalInputList = "!@#$%^&*()_+-=`~;:'\"<,>.?/|\\}]{["
def game():
attemptsMade = 0
print("Welcome to Hangman. Guess the mystery word with less than 6 mistakes.")
userInputInteger = int(input("Please enter an integer number (0<=number<10) to choose the word in the list:"))
if (0 > userInputInteger or userInputInteger > 9):
print("Index is out of range.")
game()
for i in range(0, len(wordList)):
if (userInputInteger == i):
#userChosenWord is string from wordList[i]
userChosenWord = wordList[i]
print("The length of the word is:", len(userChosenWord))
break
stringSize = len(userChosenWord)
answerStr = len(userChosenWord)
#make a temp string of _'s
for i in range(0, stringSize, 1):
answerStr[i] = '_'
keyStr = userChosenWord
def play():
guessChar = input("Please enter the letter you guess:")
if guessChar not in inputList:
print("You must enter a single, alphabetic character.")
play()
if guessChar in illegalInputList:
print("Input must be an integer.")
play()
if (guessChar == ('' or ' ')):
print("Empty input.")
play()
attemptsMade += 1
if guessChar in userChosenWord:
for i in range(0, stringSize, 1):
if (keyStr[i] == guessChar):
answerStr[i] = guessChar
print("Letters matched so far: %s", answerStr)
else:
print("The letter is not in the word.")
play()
if (answerStr == userChosenWord):
print("You have guessed the word. You win. \n Goodbye.")
sys.exit()
if (attemptsMade <= 6):
play()
if (attemptsMade > 6):
print("Too many incorrect guesses. You lose. \n The word was: %s", userChosenWord)
replayBool = bool(input("Replay? Y/N"))
if (replayBool == 'y' or 'Y'):
play()
elif (replayBool == 'n' or 'N'):
print("Goodbye.")
game()
【问题讨论】:
-
这里有很多错误。
play()几乎可以肯定不应该是递归的(不应该自称)。您也不能在play()内分配给game()(attemptsMade) 的局部变量。 -
(另外,replayBool 是一个布尔值,永远不会等于 'y'、'Y'、'n' 或 'N'...)
-
我的错误。感谢您的澄清。
-
你能解释一下为什么 play() 不应该调用自己吗?
-
每次对
play()的调用完成后,调用它的那个将恢复。这几乎肯定不是你想要的。
标签: python