简单 python 程序 - 卡住

Simple python program - stuck

我正在编写这段代码,它会说明我输入的人是否有高分。

当我在列表中输入一个人时它工作正常 "Thor",但是程序没有捕获错误并且如果名字不在列表中则不打印 "no they don't have a top score" .

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 开始并结束于ArrayLength - 1。将循环更改为:

while (Found == False) and (Current < Max):
                                    ↑

Max 应该是 3 而不是 4。 不要忘记数组是 0 索引的,所以 Names[3] 指的是第 4 个元素(也是最后一个)

并从0开始Current=0