【发布时间】:2012-02-01 12:22:49
【问题描述】:
我目前正在从一本名为“绝对初学者的 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)
【问题讨论】:
-
这是次要的,与您的问题无关,但您不需要 i = 0。即使尚未定义 i,for 循环也会在启动时自动设置循环变量。
-
@Chad 是的,你的权利。我不记得为什么我把它卡在了:S
标签: python python-3.x