-1

如何编写 python 代码,以便可以在 elif 原因中更新我的数字列表?我从一个空列表开始,然后从那里我必须询问用户他们想要添加多少新分数到列表中,然后将这些数字添加到列表中。然后我必须返回菜单系统并询问如果用户想要列表中这些数字的平均值,请按 3。在这里,我遇到的问题下方的代码是分数正在 elif 子句中更新,但是一旦我退出该子句,列表就会恢复为空。请帮忙!

4

3 回答 3

0

将绑定空列表的语句移动到循环之前。

scores = []
while 1:
   ...
于 2012-10-05T15:24:18.867 回答
0

您的 addScores 方法看起来像是返回一个列表, append 方法适用于单个元素,在您的 elif 语句中使用 extend 而不是 append 。

同样,您的 addScores 方法没有实例化要附加到的本地分数列表,因此它将返回一个空列表,因为从未实例化过。要么将你想要修改的列表传递给它,要么有一个它返回的本地列表,目前你什么都不做。

于 2012-10-05T16:08:32.677 回答
0

首先,函数不应该在while循环中定义;在循环外定义它们并传入参数。跟踪分数列表的一种简洁方法是使用全局变量,以便程序中的每个函数都可以访问它。

您修改后的代码可能如下所示:

scores = []

def addScores():
    enteredScores = []
    while True:
        numOfScores = input("How many new scores would you like to add: ")
        try:
            if int(numOfScores) > 0:
                for i in range(int(numOfScores)):
                    newInput = input("Please enter a score: ")
                    enteredScores.append(newInput)
                print(enteredScores)
                return enteredScores
            else:
                print("Please enter a positive integer.")
                continue
        except ValueError:
            print("Please enter a positive integer.")

while True:
    print("0 - Clear scores")
    print("1 - Input more scores")
    print("2 - Print scores")
    print("3 - Average scores")
    option = input("Please choose an option: ")

    if option == 0:
        scores = []
    elif option == 1:
        scores += addScores()
    elif option == 2:
        print("Scores:", scores)
    elif option == 3:
        try:
            avgScore = sum(scores)/len(scores)
            print("Average:", avgScore)
        except TypeError:
            print("Invalid score contained in list.")
    else:
        print("Quitting current program.")
        break
    replay = input("Do you wish to continue? (Y/N)")
    replay = replay.lower()
    if replay == "y" or replay == "yes":
        continue
    else:
        break

print("Goodbye!")

我添加了两个 try/except 语句。如果程序中出现错误,并且它符合上述类型之一(ValueError 和 TypeError),它不会关闭程序,而是使用 except 语句处理错误。如果您还没有涵盖这些,您可以删除它们并且程序应该可以正常工作。我还稍微清理了逻辑 - 最初,您的重播变量没有做任何事情,因此通过将其移动到循环中,它现在要么继续要么中断程序。

于 2012-10-05T16:35:47.710 回答