【问题标题】:IndexError: list index out of range, but error is inconsistent?IndexError:列表索引超出范围,但错误不一致?
【发布时间】:2016-09-02 18:49:21
【问题描述】:

我正在学习 GIS 编程课程,并为我的期末项目做一个刽子手游戏。我非常业余,所以这可能是一个我不理解的简单解决方法......这是我的代码:

import random, sys 
class Hangman:
    def __init__(self,word):
            self.word = word
            self.incorrect_letters = []
            self.letters_guessed = []

    def hangman_loss(self):
            return self.hangman_win() or (len(self.incorrect_letters) == 7)

    def hangman_win(self):
            if '_' not in self.unknown_word():
                    return True
            return False 

    def game_stats(self):
            print graphic[len(self.incorrect_letters)]
            print 'Guess the word: ' + self.unknown_word()
            print 'Incorrect Letters: ', 
            for letter in self.incorrect_letters:
                    print letter, 
            print        

    def unknown_word(self):
            rtn = ''
            for letter in self.word:
                    if letter not in self.letters_guessed:
                            rtn += '_'
                    else:
                            rtn += letter
            return rtn

    def guess(self,letter):
            if letter in self.word and letter not in self.letters_guessed:
                    self.letters_guessed.append(letter)
            elif letter not in self.word and letter not in self.incorrect_letters:
                    self.incorrect_letters.append(letter)
            else:
                    return False
            return True

graphic = [
'  +---+   \n  |   |   \n      |   \n      |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n      |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n  |   |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n  |   |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|   |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n      |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n /    |   \n      |   \n========= \n',
'  +---+   \n  |   |   \n  0   |   \n /|\\  |   \n / \\  |   \n      |   \n========= \n'
]

def rand_word():

    fruit = ['grape','apple','pear','banana','orange', 'cherry']
    return fruit[random.randint(0,len(fruit))]

def main():
    print '\nWelcome to Hangman!\nYou are allowed 7 incorrect guesses before you lose the game. \nThe theme is fruit. Good luck!\n'
    game = Hangman(rand_word())
    while not game.hangman_loss():
            game.game_stats()
            player_choice = raw_input('\nEnter a letter: ')
            if len(player_choice)>= 2:
                    while True:
                            print '\nPlease only one letter at a time'
                            retry = raw_input('Try again: ')
                            if len(retry) == 1:
                                    game.guess(retry)
                                    break
                            else:
                                    continue
            else:
                    game.guess(player_choice)

    game.game_stats()       
    if game.hangman_win():
            print '\nGreat job! You have won Hangman!'
    else:
            print '\nSorry, but you did not win the game!'
            print 'The word was ' + game.word
            print 'Good try!'
            print

    answer = raw_input('Would you like to play again? (yes or no): ')
    print
    if answer == 'yes':
            main()
    else:
            print
            print ('Thanks for playing!')
            sys.exit()

main()

有时我运行它时会抛出错误:

Traceback(最近一次通话最后一次):文件“C:/Users/Jackie Carbert/Documents/GEOG 4880/hangmanTINKERing.py”,第 135 行,在 main() 文件“C:/Users/Jackie Carbert/Documents/GEOG 4880/hangmanTINKERing.py”,第 126 行,在 main main() 文件“C:/Users/Jackie Carbert/Documents/GEOG 4880/hangmanTINKERing.py”,第 126 行,在 main main() 文件“C:/Users/Jackie Carbert/Documents/GEOG 4880/hangmanTINKERing.py”,第 88 行,在 main 游戏 = Hangman(rand_word()) 文件“C:/Users/Jackie Carbert/Documents/GEOG 4880/hangmanTINKERing.py”,第 82 行,在 rand_word return fruit[random.randint(0,len(fruit))] IndexError: list index out of range

但只是有时。显然,我看到错误是指我正在挑选一种随机水果的函数,但我看不出索引超出范围的原因、原因或方式?

【问题讨论】:

  • 你浏览过random的所有文档吗?

标签: python-2.7


【解决方案1】:

rand_word 函数的return 语句中,您需要从len(fruit) 中减去1,如下所示:

def rand_word():
    fruit = ['grape','apple','pear','banana','orange', 'cherry']
    return fruit[random.randint(0,len(fruit)-1)]

Python 列表索引从 0 开始,因此以“列表长度减一”结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2018-04-22
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多