在我的“高分”Python程序中,比较运算符有时会引发错误
这个问题是关于下面这个Python程序的 -
# High Scores
# Maintains a list of the five highest scores and the players responsible.
hiscores = [56,45,23,11]
again = "a"
def findplace(xlist, x):
# list is in descending order
for j in range(len(xlist)-1):
if x >= xlist[j]:
xlist.insert(j, x)
return xlist
while again:
print("\n", hiscores)
score = int(input("\nEnter a score (zero to exit): "))
if score >= hiscores[3]:
hiscores = findplace(hiscores, score)
elif score == 0:
again = ""
print(hiscores)
input("\nETE")
这个程序会从用户那里获取分数,如果分数足够高,就把它们添加到一个列表里。我想把进入的最低分数设置为3,所以在while循环的第三行把索引值设为3,但这样会出错。索引0、1和2都能正常工作!我到底哪里出错了呢?
2 个回答
0
问题在于,findplace
这个函数只有在分数是高分的时候才会返回一个新的列表。如果你输入的分数是 11
,而这个分数没有被插入到列表中,那么函数就不会执行到 return
语句(所以返回的是 None
)。因为你把 highscores = findplace(hiscores, score)
,这就意味着你的列表被设置成了 None
,这就导致了 TypeError
错误。
把 return xlist
移动到和 for
循环在 findplace
中同一层级可以解决这个错误(但这也暴露了你在 findplace
函数中的一个逻辑错误,这个我就留给你自己去发现了)。
0
我无法重现你提到的“入门级”分数问题。不过,因为你的列表里只有五个元素,所以你可以直接去掉入门级的检查,这样会简单很多。
while True:
print("\n", hiscores)
score = int(input("\nEnter a score (zero to exit): "))
if score == 0:
break
hiscores = findplace(hiscores, score)
另外要注意的是,你的 findplace
方法会让高分列表超过五个条目,如果分数不在前 len-1
个条目里,它可能会返回 None
。其实,你可以直接添加新的分数,然后把列表按从高到低排序,最后取前五个元素。
def findplace(xlist, x):
return sorted(xlist + [x], reverse=True)[:5]