def MasterMind():
import random
tries = 10
numbers_correct = 0
password = random.randint(1,5),random.randint(1,5),random.randint(1,5),random.randint(1,5), random.randint(1,5)
while(not numbers_correct == 5 and tries > 0):
guess = input("To access the treasure you have to guess the password!!! Guess the 5 digit password between numbers 1-5 ")
guess=guess.split()
numbers_correct = 0
tries = tries - 1
for i in range(len(password)):
if (str(password[i]) == guess[i]):
numbers_correct = numbers_correct + 1
print(str(numbers_correct) + " out of 5 correct")
print("you have " + str(tries) + " tries left")
if numbers_correct == 5:
print ("Congrats, you've gained access to the treasure!!!")
else:
print("sorry, you couldn't get to the treasure. The correct password was " + (password))
MasterMind()
我认为问题在于第11行,但我不确定。
我试图解释如何在我的univerisity教程中使用python,但我一直收到错误消息:
Traceback (most recent call last):
File "C:/Users/Owner/AppData/Local/Programs/Python/Python36-32/mastermind.py", line 25, in <module>
MasterMind()
File "C:/Users/Owner/AppData/Local/Programs/Python/Python36-32/mastermind.py", line 15, in MasterMind
if (str(password[i]) == guess[i]):
IndexError: list index out of range
有点在泡菜中,我需要一双新的眼睛试图找到问题
答案 0 :(得分:0)
执行此操作时:
guess = input("To access the treasure you have to guess the password!!! Guess the 5 digit password between numbers 1-5 ")
guess=guess.split()
... split()
将guess
转换为单词列表,以空格分隔。
因此,如果用户输入1 5 3 4 2
,即五个字,您将获得列表['1', '5', '3', '4', '2']
。然后你的代码不会引发异常。
但是如果用户键入15342
,没有空格,那只是一个单词,您将获得列表['15342']
。那么,当您尝试在循环中访问guess[1]
时,已超过列表的末尾,因此您获得了IndexError
。
如果您不希望用户键入空格,只需删除此行:
guess=guess.split()
当然,您可以尝试使其更智能,以便它可以接受两种类型的输入:
guess = [ch for ch in guess if ch.isdigit()]
但当然,如果用户拼写错误,您仍会收到错误,并且会为您1523
而不是15234
。
您可以使用try
和except
为该案例获取更好的错误处理,而不是IndexError
查杀您的程序,但这可能超出您目前所了解的范围