0

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)

4 Answers 4

1

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 <.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

while count < len(hangmanWord):

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.