int对象不支持项赋值

0 投票
1 回答
8489 浏览
提问于 2025-04-17 12:27

我现在是大学计算机专业的二年级学生,最近在做作业时遇到了一个问题。我需要制作一个和他们要求完全一样的猜字游戏(Hangman)。我想把列表格式化成带数字的样子,但我不知道怎么做,因为我刚开始接触Stack Overflow。我的问题出现在以下这段代码:

for i in range(0, stringSize, 1):
    answerStr[i] = '_'

在这里我遇到了一个错误:

int object does not support item assignment

在其他编程语言中,我可以直接创建一个大小为(用户选择的单词长度)的字符串,但在Python中,我对字符串库和动态类型的使用有些困惑。在这个作业中,我需要把当前的字符串输出为_____,如果用户猜测了字母e,而这个单词是horse,我就需要告诉用户目前匹配的字母:____e。希望这样解释能让你明白。

另外,如果你们对我的代码有任何建议或评论,请告诉我。我一直在寻找学习的机会。

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()

1 个回答

2

部分回答。这里面还有更多的内容,但关于 'int' object does not support item assignment 这个错误:

你把 answerStr 设置成了一个数字,这个数字是 len(userChosenWord),也就是 userChosenWord 的长度。

但是你试图把它当成一个列表来使用。要创建一个长度为 len(userChosenWord) 的空列表,你可以这样做:

answerStr = [0]*len(userChosenWord)

或者同样可以这样:

answerStr = [0 for i in userChosenWord]

撰写回答