2017-07-03 115 views
-1

我正在开发一个小练习程序,它可以让您为尽可能多的学生输入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() 
+0

我解决了它后不久我发布它,所以我应该已经删除它实际上 –

+0

对不起,我不清楚。我只是想确保你记得你发布了这个问题。 :)作为提问者,你没有义务标记答案。 –

+0

另外,这个程序的解决方案是一个列表。 –

回答

0

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() 
1

这是你的代码的简化版本,使用列表存储多个学生数据,然后在结尾显示这些细节,并且还计算班级的平均分(注释内联)。

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 
+0

当您尝试运行它时,您是如何看待它的?我马上在代码中遇到了一个错误我几乎完成了我只需要找出如何存储来自'avg'的输出的值 –

+1

@drewyazzie'...'是给你填满的。 –

+0

它存储在一个'list'数据结构中。请在这里找到更多:https://docs.python.org/2/tutorial/datastructures.html#more-on-lists –