Python error: “IndexError: string index out of range”

前端 未结 4 662
遇见更好的自我
遇见更好的自我 2020-12-09 04:35

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 ga

相关标签:
4条回答
  • 2020-12-09 04:54

    There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

    word = 'hello'
    so_far = "-" * len(word)       # Create variable so_far to contain the current guess
    
    while word != so_far:          # if still not complete
        print(so_far)
        guess = input('>> ')       # get a char guess
    
        if guess in word:
            print("\nYes!", guess, "is in the word!")
    
            new = ""
            for i in range(len(word)):  
                if guess == word[i]:
                    new += guess        # fill the position with new value
                else:
                    new += so_far[i]    # same value as before
            so_far = new
        else:
            print("try_again")
    
    print('finish')
    

    I tried to write it for py3k with a py2k ide, be careful with errors.

    0 讨论(0)
  • 2020-12-09 05:03

    You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

    0 讨论(0)
  • 2020-12-09 05:05

    This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

    so_far = " " * len(word)
    

    ?

    Edit:

    try something like

    print "%d / %d" % (new, so_far)
    

    before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

    0 讨论(0)
  • 2020-12-09 05:08

    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
    
    0 讨论(0)
提交回复
热议问题