在嵌套循环中查找类avg

2024-09-29 01:24:31 发布

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

我正在做一个小的练习程序,允许你输入3个测试分数,你想多少学生就输入多少,最后我希望它能计算出所有学生之间的平均分。我可以输入所有学生的名字和分数,它会给我他们的平均值,但当你输入“*”时,它只计算最后一个学生的平均值,我想知道如何让它计算出所有学生的平均成绩

def GetPosInt():     
        nameone = str

        while nameone != "*":

            nameone =(input("Please enter a student name or '*' to finish: "))

            if nameone != "*":
                scoreone = int(input("Please enter a score for " + nameone +": "))

                if scoreone < 0:
                    print("positive integers please!")
                    break

                else:
                    scoretwo = float(input("Please enter another score for "+nameone+": "))
                    scorethree = float(input("Please enter another score for "+nameone+": "))

                testscores = scoreone + scoretwo + scorethree
                avg = testscores / 3
                print("The average score for",nameone,"is ",avg)   
                classtotal = avg

            if nameone == "*":
                classavg = classtotal / 3
                print("The class average is: ",classavg)

# main
def main():
    GetPosInt()

main()

Tags: forinputifmaindef学生分数avg
2条回答

这是一个简化的代码版本,它使用列表为多个学生存储数据,然后在结尾显示这些详细信息,并计算类平均值(内联注释)。在

def GetPosInt():     
    names = [] # declare the lists you'll use to store data later on
    avgs = []

    while True:
        name = ...

        if name != "*":
            score1 = ...
            score2 = ...
            score3 = ...

            avg = (score1 + score2 + score3) / 3 # calculate the student average

            # append student details in the list
            names.append(name)  
            avgs.append(avg) 

        else:
            break

    for name, avg in zip(names, avgs): # print student-wise average
        print(name, avg)

    class_avg = sum(avg) / len(avg) # class average

当我在处理你的问题时,COLDSPEED给你发了一个解决方案。如果你想看到不同的解决方案。它在这里。。。你可以为分数设定条件。在

def GetPosInt():
    numberOfStudents = 0.0
    classtotal = 0.0
    classavg = 0.0
    while(True):
        nam = (raw_input("Please enter a student name or '*' to finish "))
        if(nam == '*'):
            print("The average of the class is " + str(classavg))
            break
        numberOfStudents += 1.0
        scoreone = float(input("Please enter the first score for " + str(nam) + ": "))
        scoretwo = float(input("Please enter the second score for " + str(nam) + ": "))
        scorethree = float(input("Please enter the third score for " + str(nam) + ": "))
        testscores = scoreone + scoretwo + scorethree
        avg = testscores / 3.0
        print("The average score for " + str(nam) + " is " + str(avg))
        classtotal += avg
        classavg = classtotal / numberOfStudents

def main():
    GetPosInt()
main()

相关问题 更多 >