我正在编写这段代码,它会显示我输入的人是否具有高分。
当我在列表中输入一个人(例如“Thor”)时,它工作正常,但是如果该名字不在列表中,程序不会捕获错误,也不会打印“不,他们没有最高分”列表。
Names = ['Ben', 'Thor', 'Zoe', 'Kate']
Max = 4
Current = 1
Found = False
PlayerName = input("What player are you looking for? ")
while (Found == False) and (Current <= Max):
if Names[Current] == PlayerName:
Found = True
else:
Current = Current + 1
if Found == True:
print("Yes, they have a top Score")
else:
print("No, They do not have a top score")
因此,如果输入 James,则会输入此错误
if Names[Current] == PlayerName:
IndexError: list index out of range"
我该如何解决这个问题?谢谢。
最佳答案
数组索引从 1
开始,而在 Python、C、C++ 和许多语言中,数组索引(例如列表)从 0
开始并以数组长度 - 1
。将循环更改为:
while (Found == False) and (Current < Max):
↑
关于python - 简单的Python程序-卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557090/