Reputation: 19
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)
Upvotes: 0
Views: 42
Reputation: 11454
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))
Upvotes: 0
Reputation: 112
String indexes are from 0
to len(string)-1
;
you just need to change your loop like this:
while count < len(hangmanWord):
Upvotes: 0
Reputation: 1957
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 <
.
Upvotes: 1
Reputation: 5
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.
Upvotes: 0