Python error: string index out of range python

Python

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)

 


If you want to unleash your potential in this competitive field, please visit the Python course page for more information, where you can find the Python tutorials and Python frequently asked interview questions and answers as well.

1
Answers

Replies


The indentation is wrong in your code. Try the below code.



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 topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
WhatsApp
To Top