Rubykuby

Student.py

Sep 20th, 2013
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. class Student(object):
  2.    
  3.     def __init__(self, course):
  4.         """Initialises object 'Student' with a course name.
  5.        """
  6.         self.course = course
  7.         self.subjectList = []
  8.    
  9.     def addSubject(self, *args):
  10.         """Defines (a) new object(s) from class 'Student'.
  11.        Adds that object to self.subjectList.
  12.        """
  13.         for newSubjectName in args:
  14.             self.subjectList.append(self.Subject(newSubjectName))
  15.    
  16.     def printStats(self):
  17.         """Prints the names of the subjects in subjectList."""
  18.         for i in range(len(self.subjectList)):
  19.             print("Subject " + str(i+1) + ": " + self.subjectList[i].subjectName)
  20.        
  21.     def avgMark(self):
  22.         """Loops through all subjects in subjectList.
  23.        Appends the sum of the subject's marks to total.
  24.        Appends the amount of marks in the subject to count.
  25.        Returns the average.
  26.        """
  27.         total = 0
  28.         count = 0
  29.        
  30.         for subject in self.subjectList:
  31.             total += sum(subject.marks)
  32.             count += len(subject.marks)
  33.         return total / count
  34.    
  35.     class Subject(object):
  36.        
  37.         def __init__(self, subjectName):
  38.             self.subjectName = subjectName
  39.             self.marks = []
  40.        
  41.         def assignMarks(self, *args):
  42.             """Takes marks from *args. Appends them to self.marks.
  43.            Marks must be between 1 and 10. If they're not, an exception will be raised.
  44.            """
  45.             for mark in args:
  46.                 if mark >= 1 and mark <= 10:
  47.                     self.marks.append(mark)
  48.                 else:
  49.                     raise Exception("Incorrect value for mark")
  50.                
  51. def main():
  52.     s = Student("Software engineering")
  53.     s.addSubject("Programming", "Analytics", "Maths", "Computer Organisation")
  54.     s.printStats()
  55.     s.subjectList[0].assignMarks(7, 3.8, 10)
  56.     s.subjectList[1].assignMarks(6.7, 5, 6)
  57.     s.subjectList[2].assignMarks(7.3, 1)
  58.     s.subjectList[3].assignMarks(8.5)
  59.     print(s.avgMark())
  60.  
  61. if __name__ == "__main__":
  62.     main()
Advertisement
Add Comment
Please, Sign In to add comment