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

前端 未结 4 672
遇见更好的自我
遇见更好的自我 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 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
    

提交回复
热议问题