I'm currently learning python from a book called 'Python for the absolute beginner (third edition)'. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.
Here is the code that is causing the problem:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
This is also the error it returns:
new += so_far[i]
IndexError: string index out of range
Could someone help me out with what is going wrong and what I can do to fix it?
edit: I initialised the so_far variable like so:
so_far = "-" * len(word)
The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.
The Java String class charAt() method returns a char value at the given index number. The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.
We saw how we can generate an IndexError by indexing beyond the end of a string. Is it possible to construct an index that goes too far to the left, before the start of the string? Yes, that is possible. Given a string s , s[-(len(s)+1)] will generate an IndexError since it goes too far to the left.
Generally, list index out of range means means that you are providing an index for which a list element does not exist. Now, for this exercise they require you to create a generic function for an unknown number of strings in a list(i.e. any amount of strings in a list) not just 2 strings as provided in the exercise.
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With