编写计算测验成绩表总和的程序

2024-04-26 18:02:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我正在研究的问题:

问题:最终测验分数的计算方法是将所有分数相加,但最低的两个分数除外。编写一个程序,利用列表打印出最后的分数。在

尝试:我认为我的一切都是正确的,只是我不确定应该在“main”函数下编写什么代码。这是我的代码:

def main():
    scores = readFloats(values)
    removeMinimum(scores)
    removeMinimum(scores)
    total = sum(scores)
    print("The final score is", total)


def readFloats(values):
    values = []
    userInput = input("Please enter a value or Q to quit: ")
    while userInput != "Q":
        n = float(userInput)
        values.append(n)
        userInput = input("Please enter a value or Q to quit: ")

    return values

def removeMinimum(values):
    smallest = values[0]
    for i in range(len(values)):
        if values[i] < smallest:
            smallest = values[i]

    values.remove(smallest)

main()

当我试图运行这个程序时,它说'values'这个名称没有在'main'函数中定义。我不知道怎样才能把参考号找对。应提示用户输入值,如果输入的值为8、4、7、8.5、9.5、7、5、10,则输出应为50。有人能告诉我我的错误在哪里吗?在


Tags: 函数代码程序inputmaindef分数total
3条回答

您的错误是由于您在第一次调用函数readFloats(values)时使用了名称values,而没有为values提供实际值。在

由于用户使用readFloats函数输入值,所以实际上不需要向它传递参数。从readFloats中删除参数values将使其正确执行:

# empty parameter list
def readFloats():
    # body of readFloats() 

另外,请注意Python附带了一组^{}函数,它们在这样的上下文中非常有用。像min()max()这样的函数将派上用场。在

@Dimitris Jim: (It's very good explanation thats why I use it)
Your error is due to the fact that you are using the name values in your first call to function readFloats(values) while not having supplied an actual value for values.

Since the user inputs values using the readFloats function, you really don't need to pass a parameter to it. Removing the parameter values from readFloats will make it execute correctly:

只需简单地通过List Comprehension

>>> score = [8, 4, 7, 8.5, 9.5, 7, 5, 10]
>>> score.sort()
>>> score
[4, 5, 7, 7, 8, 8.5, 9.5, 10]
>>> sum(score[2:])
50.0
>>> 

根据您的代码:

^{pr2}$

输出:

Please enter a value or Q to quit: 4
Please enter a value or Q to quit: 8
Please enter a value or Q to quit: 7
Please enter a value or Q to quit: 8.5
Please enter a value or Q to quit: 9.5
Please enter a value or Q to quit: 7
Please enter a value or Q to quit: 5
Please enter a value or Q to quit: 10
Please enter a value or Q to quit: Q
('The final score is', 50.0)

在Python中,您可以通过在变量中添加一些内容来实例化它:您还没有这样做。您正在向readFloats方法传递名为“values”的内容,但没有在其中放入任何内容,因此该变量不存在,Python也找不到它。在传递给readFloats之前,将一些内容放入“values”中。告诉Python这是一个float数组。在

相关问题 更多 >