Python程序,它获取测试分数并输出以下内容:

时间:2014-11-24 03:20:20

标签: python

我必须编写一个程序,其中包含用户输入的测试分数和输出,所有输入的分数,平均分数,最大和最低分数,所有分数超过50,以及所有分数超过平均值。我得到一个错误,分数没有被识别,我不知道我在做什么错误调用列表?我还是编程的新手,并且正在努力调用函数。谢谢。

def main():
    test = getscores()
    avg = average(test)
    top = large(test)
    over = passed(test)
    greater = above(test, avg)

    print("The test scores are,", test)
    print("The average test score is,", avg)
    print("The largest and lowest score are," top)
    print("All the PASS scores are,", over)
    print("All the scores above average are,", greater)

def getscores():
    scores = []     
    xStr = input("Enter a test score in the range 0-100: (<Enter> to quit)")
    while xStr != "":
        x = eval(xStr)
        scores.append(x)   
        xStr = input("Enter a test score int he range 0-100: (<Enter> to quit)")
    return scores

def average(scores):
    sum = 0.0
    for i in scores:
        sum = sum + scores
        avg = sum / i
    return avg

def large(scores):
    largest = max(scores)
    lowest = min(scores)
    return largest, lowest

def passed(scores):
    for i in scores:
        PASS = i > 50
    return PASS

def above(scores, avg):
    high = scores > avg
    return high

main()

1 个答案:

答案 0 :(得分:1)

这里有一个清单:


eval()是一个更好的选择时,您可能没有想要致电int()来输入值。前者用于评估任意表达式,例如1 + 2variable * 7


此外,如果您使用的是Python 2,则需要raw_input()而不是input()


average功能中,除非您拥有完整的金额,否则无需计算平均值。最重要的是,您尝试添加带有列表sum的整数scores,而您应该添加scores的元素,即i。将其重写为:

def average(scores):
    sum = 0.0
    for i in scores:
        sum = sum + i
    avg = sum / len(scores)
    return avg

由于large()会返回两个值,而您想要同时打印这两个值,因此您应将其称为:

(top, bottom) = large(test)

并用以下内容打印:

print("The largest and lowest score are ", top, " and ", bottom)

您的passed()函数返回单个真值而不是通过的人数。它可以写成:

def passed(scores):
    quant = 0
    for i in scores:
        if i > 50:
            quant = quant + 1
    return quant

同样处理above()函数,它会更好:

def above(scores,avg):
    quant = 0
    for i in scores:
        if i > avg:
            quant = quant + 1
    return quant

通过所有这些更改,您将看到以下内容:

Enter a test score in the range 0-100: (<Enter> to quit)52
Enter a test score int he range 0-100: (<Enter> to quit)45
Enter a test score int he range 0-100: (<Enter> to quit)8
Enter a test score int he range 0-100: (<Enter> to quit)
('The test scores are,', [52, 45, 8])
('The average test score is,', 35.0)
('The largest and lowest score are', 52, 'and', 8)
('All the PASS scores are,', 1)
('All the scores above average are,', 2)

如果您想要返回实际列表的通过和高于平均分数,您可以构建这样的列表并附加到它,就像您在输入时完成的那样得分:

def passed(scores):
    slist = []
    for i in scores:
        if i > 50:
            slist.append(i)
    return slist

def above(scores,avg):
    slist = []
    for i in scores:
        if i > avg:
            slist.append(i)
    return slist

或者更好的是,重构所以你只需要一个:

def above(scores,threshold):
    slist = []
    for i in scores:
        if i > threshold:
            slist.append(i)
    return slist

over = above(test,50)
greater = above(test, avg)