Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON program help with code. This is the code I have so far.. Write a class th

ID: 3677292 • Letter: P

Question

PYTHON program help with code. This is the code I have so far..

Write a class that represent an individual student. The class needs to have the following instance variables:

a unique id

a name in the form "smith, john"

two exam scores representing a midterm and an final

Your class will need a constructor to create each student so the user can enter the student ID, name, and exam scores. The class will also need the following methods.

a method to calculate the letter grade for the student based on the average of the exam scores. Use the grading scale used for this class.

a method to return the name, two exam scores, and the letter grade for a student.

You'll need a dictionary that will represent a particular course, like CIT101 for example. We'll add student instances to this dictionary so that the dictionary will hold the information for that course.

Each student instance will be held in the dictionary using the student ID as a key. Assume the dictionary is called CIT101, and the class is called Student, so calling
    Student(id, name, midterm, final)
creates an instance of the student class. Then if we were hardcoding all this it might look like the following.

CIT101 = {}        # create the containing dictionary
# add student instance to CIT101 dictionary
CIT101["123"] = Student("123", "smith, john", 78, 86)

Your program needs to have a 5-option menu that should look very much like the following.

"""
    try except blocks and file existance
"""

import pickle
class StudentClass(object):

    def __init__(self, stuid, name, midterm, final): # create student instance
        self.id = stuid
        self.name = name
        self.midterm = midterm
        self.final = final
        self.grade = grade

    def calcGrade(self):
        try:
            return round(self.midterm + self.final) / 2
        except ZeroDivisionError:
            print("Division by zero, student ID = ", self.id)
        except Exception as ex:
            print("Error: ", ex.args)

        return 0

    def gradeAvg:
             grade=getGrade(avg)
         if(grade=='A'):
             gradeA=gradeA+1
         elif(grade=='B'):
             gradeB=gradeB+1
         elif(grade=='C'):
             gradeC=gradeC+1
         elif(grade=='D'):
             gradeD=gradeD+1
         elif(grade=='F'):
             gradeF=gradeF+1
         print(record[0], grade)

    def getStudentData(self):       # return student data as a formatted string
        grade = self.calcGrade()     # calculate Grade
        return "%-4s %-15s %5d %5d %7.1f" % (self.id, self.name, self.midterm,
                                                              self.final, self.grade)

# ---- end class definition ----------
def displayStudents(students):
    if len(students) > 0:
        print()
        print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
                                                            "Final", "Grade"))
        for student in students:
            print(students[student].getStudentData())
    else:
            print()
            print("No Students have been added yet.")

def addStudent(d):
    try:
        student_id = input("Enter student ID: ")
        name = input("Enter name: ")
        midterm = int(input("Enter midterm: "))
        final = float(input("Enter final: "))
        # instantiate student, add to dictionary
        d[student_id] = StudentClass(student_id, name, midterm, final)  
    except ValueError:
        print('Some data entered is invalid, no data accepted.')

    return d      # if ok, return modified dictionary

def readData1(fn):         # returns a dictionary

    try:
        f = open(fn, "rb")
        d = pickle.load(f)      # get a dictionary of student objects
        f.close()
    except IOError:
        d = {}                  # else no file yet, create empty dictionary
    return d                    # return the dictionary

def readData():
    totals = {} # create empty dictionary
    try:
        f = open("classTotals.txt", "rb")     # open binary read mode
        totals = pickle.load(f)               # reads a dictionary from file
        f.close()                             # everything went well

    except IOError:
        print("Creating empty dictionary...") # file does not exist, yet

    except:
        print("An unexpected error occured.")

    return totals # if file doesn't exist return an empty dictionary

def deleteStudent(t, student_id):
    try:
        del t[student_id]
        print("student deleted")
    except:
        print("student ID not valid")

    return t

def displayData(totals):
    if len(totals) == 0:
        print("No courses have been entered")
        return

    grandTotal = 0
    print()
    for course in totals:
        print("%-7s %4d" % (course, totals[course]))
        grandTotal += totals[course]
    print()
    print("total for all classes: " + str(grandTotal)) # print total enrollment


def addCourse(d):          # d is our dictionary of data
    while True:
        name = input("Enter course name, q to quit: ")
        if name == 'q':
            break

        enrollment = input("Enter course enrollment: ")

        if isinstance(name, str) and enrollment.isdigit():
            enrollment = int(enrollment)
            d[name] = enrollment   # add key and value to dictionary
        else:
            print("Either course name or enrollment data has issues")
            print()

    return d              # return the dictionary


def storeData(data):
    f = open("classTotals.txt", "wb")   # open binary write mode
    pickle.dump(data, f) # dump (store) the dictionary to file f
    f.close
def storeData1(fn, d):
    f = open(fn, "wb")      # open file and store
    pickle.dump(d, f)
    f.close()

def main():
   
    fn = "students.txt"
    students = readData(fn)    # students is a dictionary of student objects
    totals = readData()   # otherwise we read the dictionary of file data
    while True:
        print("""
    Menu options. Choose 1, 2, 3, 4, 5, 6, or 7
    1. Create a new course
    2. Display course data
    3. Display All Student Data
    4. Add a Student
    5. Display a particular Student
    6. Delete a Student
    7. Save and exit
    """)
    opt = input("Enter your choice, 1, 2, or 3: ")

    if opt == "1":
        totals = addCourse(totals)   # add an item or items to the dictionary
    elif opt == "2":
        displayData(totals)      # display enrollments
        opt = input("Enter your choice, 1, 2, 3, 4, or 5: ")

    elif opt == "3":               # display all Students
        displayStudents(students)

    elif opt == "4":             # add a Student
        students = addStudent(students)

    elif opt == "5":             # display a single Student
        print()
        student_id = input("Enter student ID: ")
        print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
                                              "Final", "MGP"))
        print(students[student_id].getStudentData())
       
    elif opt == "6":             # delete a Student
        print()
        student_id = input("Enter ID of student to delete: ")
        students = deleteStudent(students, student_id)
       
    elif opt == "7":             # save and exit program
        storeData(fn, students)
        storeData1(fn, d):
            f = open(fn, "wb")      # open file and store
            pickle.dump(d, f)
            f.close()
       
        print("Goodbye")
        print()
        break

   
    else:
        print("Invalid entry, please re-enter your choice")
        print()



main() # call main(), execute the program





     

Explanation / Answer

heres the code i added few functions too

import pickle
class StudentClass(object):

     def __init__(self, stuid, name, midterm, final): # create student instance
         self.id = stuid
         self.name = name
         self.midterm = midterm
         self.final = final
         self.grade='X'

     def calcGrade(self):
         try:
             avg=round((self.midterm + self.final) / 2)
             if(avg>75):
                 return 'A'
             if(avg<=75 and avg>65):
                 return 'B'
             if(avg<=65 and avg>55):
                 return 'C'
             if(avg<=55 and avg>45):
                 return 'D'
             if(avg<=45):
                 return 'F'
         except ZeroDivisionError:
             print("Division by zero, student ID = ", self.id)
         except Exception as ex:
             print("Error: ", ex.args)

         return 0
   
   

     def getStudentData(self):       # return student data as a formatted string
         self.grade = self.calcGrade()     # calculate Grade
         return "%-4s %-15s %5d %5d %-4s" % (self.id, self.name, self.midterm,
                                                               self.final, self.grade)

# ---- end class definition ----------
def displayStudents(students):
     if len(students) > 0:
         print()
         print("ID Name         Midterm    Final    Grade")
         for student in students:
             print(students[student].getStudentData())
     else:
             print()
             print("No Students have been added yet.")

def addStudent(d):
     try:
         student_id = input("Enter student ID: ")
         name = input("Enter name: ")
         midterm = int(input("Enter midterm: "))
         final = float(input("Enter final: "))
         # instantiate student, add to dictionary
         d[student_id] = StudentClass(student_id, name, midterm, final)
     except ValueError:
         print('Some data entered is invalid, no data accepted.')

     return d      # if ok, return modified dictionary

def readData1(fn):         # returns a dictionary

     try:
         f = open(fn, "rb")
         d = pickle.load(f)      # get a dictionary of student objects
         f.close()
     except IOError:
         d = {}                  # else no file yet, create empty dictionary
     return d                    # return the dictionary

def readData():
     totals = {} # create empty dictionary
     try:
         f = open("classTotals.txt", "rb")     # open binary read mode
         totals = pickle.load(f)               # reads a dictionary from file
         f.close()                             # everything went well

     except IOError:
         print("Creating empty dictionary...") # file does not exist, yet

     except:
         print("An unexpected error occured.")

     return totals # if file doesn't exist return an empty dictionary


def deleteStudent(t, student_id):
     try:
         del t[student_id]
         print("student deleted")
     except:
         print("student ID not valid")

     return t

def displayData(totals):
     if len(totals) == 0:
         print("No courses have been entered")
         return

     grandTotal = 0
     print()
     for course in totals:
         print("%-7s %4d" % (course, totals[course]))
         grandTotal += totals[course]
     print()
     print("total for all classes: " + str(grandTotal)) # print total enrollment

def findcourse(course,totals):
    for courses in totals:
        if course==courses:
            return 1
    return 0
def addCourse(d):          # d is our dictionary of data
     while True:
         name = input("Enter course name, q to quit: ")
         if name == 'q':
             break

         enrollment = input("Enter course enrollment: ")

         if isinstance(name, str) and enrollment.isdigit():
             enrollment = int(enrollment)
             d[name] = enrollment   # add key and value to dictionary
         else:
             print("Either course name or enrollment data has issues")
             print()

     return d              # return the dictionary


def storeData(data):
     f = open("classTotals.txt", "wb")   # open binary write mode
     pickle.dump(data, f) # dump (store) the dictionary to file f
     f.close

def main():
   
     fn = "students.txt"
     students = readData1(fn)    # students is a dictionary of student objects
     totals = readData()   # otherwise we read the dictionary of file data
     courses = {}
     while True:
         print("""
     Menu options. Choose 1, 2, 3, 4, 5, 6, or 7
     1. Create a new course
     2. Display course data
     3. Display All Student Data
     4. Add a Student
     5. Display a particular Student
     6. Delete a Student
     7.Add course to student instance
     8. Save and exit
     """)
         opt = input("Enter your choice, 1, 2, or 3...: ")

         if opt == "1":
             totals = addCourse(totals)   # add an item or items to the dictionary
         elif opt == "2":
             displayData(totals)      # display enrollments
             opt = input("Enter your choice, 1, 2, 3, 4, or 5: ")

         elif opt == "3":               # display all Students
             displayStudents(students)

         elif opt == "4":             # add a Student
             students = addStudent(students)

         elif opt == "5":             # display a single Student
             print()
             student_id = input("Enter student ID: ")
             print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
                                               "Final", "MGP"))
             try:
                 print(students[student_id].getStudentData())
             except:
                 print("Student doesnt exist ")
       
         elif opt == "6":             # delete a Student
             print()
             student_id = input("Enter ID of student to delete: ")
             students = deleteStudent(students, student_id)
       
         elif opt == "8":             # save and exit program
             storeData(fn, courses)
             def storeData1(fn, d):
                 f = open(fn, "wb")      # open file and store
                 pickle.dump(d, f)
                 f.close()
              print("Goodbye")
              print()
              break
         elif opt=="7":
              student_id = input("Enter ID of student to add to course: ")
              print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
                                               "Final", "MGP"))
              course=input("Enter course name: ")
              l=findcourse(course,totals)
              if(l==1):
                   
                  try:
                      courses[course]=students[student_id].getStudentData()
                
                  except:
                      print("Student or course doesnt exist ")
             

  
     else:
         print("Invalid entry, please re-enter your choice")
         print()
main()