使用Python 3.6中的函数和列表计算平均成绩

时间:2017-03-19 20:32:01

标签: python python-3.x

我尝试做的是根据用户输入制作名单和成绩列表,然后显示列表以及在表格中组织列表,最后计算平均成绩

所以我希望我的脚本提示用户输入名称和成绩,然后将它们存储在列表中。此提示将重复,直到用户输入空字符串(只需在提示输入名称时按Enter键)。

我在存储列表时遇到问题,并在输入空字符串时启动打印和计算。

这是我到目前为止所得到的:

    #   Importing Python tabulate package
from tabulate import tabulate

#   Defining functions
def getRec():
    #   Get a record from user input, return an empty of the user entered an empty string as input
    name = str(input("Enter a name: "))
    if name != "":
        score = int(input("Enter the grade of " + name +": "))
        return name,score
    else:
        return None

def addList(List,rec):
    #   Add a rec into the list
    List = tuple(rec)
    return List,rec

def putRec(List):
    #   Print a record in a specific format
    print(List)

def printTable(List):
    #   Print a table with a heading
    print(tabulate(List,showindex="always",headers=["Index","Name","Grade"]))

def average(List):
    #   Computes the average score and return the value
    total = List[0][1]
    avg = total/len(List)
    print("Average Grade: ",avg)

#   Main function

List = []
rec = []
while True:
    rec = list(getRec())
    List = addList(List,rec)

    if rec == None:
        for index in range(len(List)):
            print()
            putRec(List)
            print()
            printTable(List)
            print()
            average(List)
        break

当我尝试启动打印和计算时,出现错误,因为我返回了“无”字样。在我的第一个功能。但如果我返回零,则列表变为零。我需要帮助尝试启动我的其他功能,并可能修复我根据输入创建列表的方式。

感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

在将记录添加到列表之前,您需要检查getRec()是否返回None:

#   Main function

List = []
rec = []
while True:
    result = getRec()
    print(result)

    if result == None:
        for index in range(len(List)):
            print()
            putRec(List)
            print()
            printTable(List)
            print()
            average(List)
        break

    else:
        rec = list(result)
        addList(List,rec)

您的addList功能中也存在错误。您必须使用.append()方法将项​​目添加到列表中。那么就不需要返回值。

def addList(List,rec):
    #   Add a rec into the list
    List.append(tuple(rec))

代码应该在没有任何问题的情况下运行这2个更改,但平均成绩仍然是错误的。您需要使用for循环来计算所有等级的总和:

def average(List):
    #   Computes the average score and return the value
    total = 0

    for r in List:
        total += r[1]

    avg = total/len(List)
    print("Average Grade: ",avg)

希望有所帮助:)

编辑:

不确定为什么使用循环打印整个表格。你根本不需要它。这是没有循环的代码:

while True:
    result = getRec()
    print(result)

    if result == None:
        print()
        putRec(List)
        print()
        printTable(List)
        print()
        average(List)
        break

    else:
        rec = list(result)
        addList(List,rec)
相关问题