Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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)

2 Answers

0 votes
by (106k points)

To get rid of this error you can try the following ways:-

if guess in word: 

print("\nYes!", guess, "is in the word!") 

new = "" 

i = 0 

for i in range(len(word)): 

if guess == word[i]: 

new += guess 

else: 

new += so_far[i] 

so_far = new 

Learn python with the help of this python training and also visit the python interview questions.

0 votes
by (140 points)

In Python, a string is a single-dimensional array of characters. The string index out of range means that the index you are trying to access does not exist. In a string, that means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string. Indexes in Python programming start at 0. This means that the maximum index for any string will always be length-1. There are several ways to account for this. Knowing the length of your string (using len() function)could certainly help you to avoid going over the index.

Wanna become an Expert in python? Come & join our Python Certification course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...