Home > database >  Python index error for hangman game program
Python index error for hangman game program

Time:12-14

This is a piece of the program for a game of hangman. I am trying to iterate through the hangman word and print the letter guessed by the user if it matches at that index. If it does not it will print an underscore. I am getting the following error for the second if condition: IndexError: string index out of range

while(guessTracker >= 0):
     letterGuess= input("Enter a letter for your guess: ")
     count=0
     wordGuess=""

  if letterGuess in hangmanWord:
     while count<= len(hangmanWord):
        if hangmanWord[count]==letterGuess: 
            wordGuess= wordGuess  letterGuess
            right= right 1
        else:
            wordGuess= wordGuess   "_ "

        count =1
    print(wordGuess)

CodePudding user response:

In Python (and most other programming languages) string indexes start at 0 so the last position is len(hangmanWord)-1.

You can fix it just by changing <= to <.

CodePudding user response:

Try

while count<= len(hangmanWord)-1:

Because the string's length will never reach the real length (for example: if the word is "hangman", it has a length of 7, but the count starts from 0, and goes up to a maximum of 6, therefor not being able to ever reach the 7th char.

CodePudding user response:

String indexes are from 0 to len(string)-1; you just need to change your loop like this:

while count < len(hangmanWord):

CodePudding user response:

Indexes are 0-based so you index a string from index 0 up to len(hangmanWord) - 1.

hangmanWord[len(hangmanWord)] will always raise an IndexError.

You should also give a look to the enumerate function that can help with that.

wordGuess = ["_"] * len(hangmanWord)

for index, letter in enumerate(hangmanWord):
    if letterGuess == letter:
        wordGuess[index] = letter

print("".join(wordGuess))  

CodePudding user response:

You must crosscheck your hangmanWord. Most probably your hangmanWord parameters getting null.

  • Related