簡體   English   中英

For 循環中的“列表索引超出范圍”錯誤,我嘗試通過 len() 定義長度並附加

[英]"List index out of range" error in For loop, where I tried defining the length through len() and appending

我是 Python 的初學者,我想制作一個 Hangman 游戲來掌握這門語言。

print('You have 5 turns to guess the word.')
turn = int(5)
word = str('secret')
i = int(0)
time.sleep(1)
for i in range(len(word)):
    print('_', end='')
    time.sleep(0.3)
print()
time.sleep(1)
current = list()
while turn != 0:
    if turn > 1:
        print('You have', turn, 'guesses.')
    else:
        print('You have', turn, 'guess.')
    guess = input('Enter your guess.')
    for i in range(len(word)):
        if guess == word[i]:
            print(guess, end='')
            current[i] = guess
        else:
            print('_', end='')
            current[i] = '_'
    print(current)
    turn -= 1

在上面的代碼中,我在 for 循環中收到“列表索引超出范圍”錯誤。 我認為問題在於列表長度在開始時沒有定義。 所以,我添加了這個:

len(current) = len(word)

但是,這並沒有幫助。 然后我嘗試在第一輪追加:

        if j == 0:
            if guess == word[i]:
                print(guess, end='')
                current.append(guess)
            else:
                print('_', end='')
                current.append('_')
            j=1
        else:
            if guess != word[i]:
                print(current[i], end='')
            elif current[i] != '_':
                print(guess, end='')
                current[i] = word[i]
            else:
                print(guess, end='')
                current[i] = '_'

即使這不起作用,現在我迷路了。

您可能沒有將current定義為空列表,因為您無法在特定索引處分配某些字母,因為它們不存在,請執行

current = ['_'] * len(word)

那么你的if/else是錯誤的,因為它在current只分配了你剛剛給出的字母,所以你一直把_放在找到的前三個字母上。

您可能只有一個if for 好字母,用於更改下划線,只需在for循環后打印current ,不需要執行兩次(在循環內)

current = ['_'] * len(word)
while turn != 0:
    if turn > 1:
        print('You have', turn, 'guesses left.')
    else:
        print('You have', turn, 'guess left.')
    guess = input('Enter your guess: ')
    for i in range(len(word)):
        if guess == word[i]:
            current[i] = guess
    print("".join(current))
    turn -= 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM