如何解决Python程序有时会退出,并显示“ IndexError:字符串索引超出范围”,有时运行良好
我正在学习Python,并决定升级一个版本的hangman游戏,该版本在我所观看的其中一门课程中用作示例,结果代码如下:
import random
word_dictionary = {
1: "mouse",2: "house",3: "show",4: "see",5: "leave",6: "shower",7: "showcase",8: "coding",9: "elephant",10: "apartment",}
random_number = random.randint(1,10)
random_word = word_dictionary[random_number]
secret_word = random_word
word_len = len(secret_word)
guess = None
tip = 0
tip_num = None
tip_prevIoUs = None
tip_position = None
tip_model_formula = "_"*word_len
tip_model_list = list(tip_model_formula)
send_tip = None
print("Word has",word_len," letters")
while guess != secret_word:
guess = input("Enter your guess: ")
if guess != secret_word:
print("Wrong answer! Try again!")
tip += 1
if tip == 5:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_prevIoUs = tip_num
print("here's a tip:\n" + send_tip)
if tip == 10:
tip_num = random.randint(0,word_len)
while tip_num == tip_prevIoUs:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_prevIoUs = tip_num
print("here's a tip:\n" + send_tip)
if tip == 15:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_prevIoUs = tip_num
print("here's a tip:\n" + send_tip)
if tip == 16:
print("You lost!")
exit()
print("You win!")
(这是从字典中随机选择一个单词作为秘密单词,并让玩家对其进行猜测,每5次尝试,玩家经过16次尝试后获得1个提示,即单词的一个字母,您将丢失并且必须重新启动。)
当我运行它时,有时它会按预期运行,但有时会退出并显示以下错误:
Traceback (most recent call last):
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\pydevd.py",line 1448,in _exec
pydev_imports.execfile(file,globals,locals) # execute the script
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py",line 18,in execfile
exec(compile(contents+"\n",file,'exec'),glob,loc)
File "C:/Users/rafae/PycharmProjects/Beginning/Beg.py",line 55,in <module>
tip_position = secret_word[tip_num]
IndexError: string index out of range
我不知道为什么这会随机发生,并且一直试图找出一个小时没有成功。 感谢您的任何事先帮助。
解决方法
您的错误在这里:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
randint
返回其第一个和第二个参数之间的数字,包括这两个参数。这意味着它可以返回word_len
的结果,该结果比secret_word
的末尾晚一个。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。