IndexError:列表索引超出范围,但错误不一致?

时间:2016-05-07 21:01:34

标签: python-2.7

我正在介绍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行,in          main()文件“C:/ Users / Jackie Carbert / Documents / GEOG 4880 / hangmanTINKERing.py”,第126行,主要       main()文件“C:/ Users / Jackie Carbert / Documents / GEOG 4880 / hangmanTINKERing.py”,第126行,主要       main()文件“C:/ Users / Jackie Carbert / Documents / GEOG 4880 / hangmanTINKERing.py”,第88行,主要       game = Hangman(rand_word())文件“C:/ Users / Jackie Carbert / Documents / GEOG 4880 / hangmanTINKERing.py”,第82行,in   rand_word       return fruit [random.randint(0,len(fruit))] IndexError:列表索引超出范围

但有时候。显然我看到错误是指我正在选择其中一个随机成果的函数,但我不知道索引是什么,为什么或如何超出范围?

1 个答案:

答案 0 :(得分:0)

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

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

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