我目前正在从一本名为《 Python绝对入门》(第三版)的书中学习python。书中有一个练习,概述了一个子手游戏的代码。我遵循了这段代码,但是我在程序的中间不断返回错误。
这是导致问题的代码:
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
这也是它返回的错误:
new += so_far[i] IndexError: string index out of range
有人可以帮助我解决出现的问题以及如何解决该问题吗?
编辑:我像这样初始化so_far变量:
so_far = "-" * len(word)
您好像缩进so_far = new得太多了。尝试这个:
so_far = new
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