gpt4 book ai didi

Python 错误 : "IndexError: string index out of range"

转载 作者:太空狗 更新时间:2023-10-29 17:15:51 31 4
gpt4 key购买 nike

我目前正在通过一本名为“Python for the absolute beginner (third edition)”的书学习 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 缩进太多了。试试这个:

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

关于Python 错误 : "IndexError: string index out of range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712659/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com