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

PYTHON program help with code. The code I have so far is below half of it works

ID: 3677983 • Letter: P

Question

PYTHON program help with code. The code I have so far is below half of it works but I can’t get it to print.

Write a class that represents 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 a 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, at least.

•              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.


import pickle
class StudentClass(object):
    def __init__(self, student_id, name, midterm, final): # create student instance
        self.id = student_id
        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 "%5i %-5s %5f %5f %-4s" % (self.id, self.name, self.midterm, self.final, self.grade)


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(s, student_id):
    try:
        del s[student_id]
        print("student deleted")
    except:
        print("student ID not valid")
    return s

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 storeData1(fn, d):
    f = open(fn, "wb")      # open file and store
    pickle.dump(d, f)
    f.close()
    print("Goodbye")
    print()
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, 7, or 8:
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, 3, 4, 5, 6, 7, or 8: ")
        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, 5, 6, 7, or 8: ")
        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", "Grade"))
            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=="7":
            student_id = input("Enter ID of student to add to course: ")
            print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
                                                 "Final", "Grade"))
            course=input("Enter course name: ")
            l=findcourse(course,totals)
            if(l==1):
                try:
                    courses[course]=students[student_id].getStudentData()
                except:
                    print("Invalid entry, please re-enter your choice")
                    print()
                else:
                    print("Student or course doesnt exist ")
                    print()

        elif opt == "8":             # save and exit program
            storeData(fn, courses)
            storeData(totals) # pickle the dictionary
            break
       
        else:
            print("Invalid entry, please re-enter your choice")
            print()

main()

Explanation / Answer

import pickle
class StudentClass(object):
def __init__(self, student_id, name, midterm, final): # create student instance
self.id = student_id
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 "%5i %-5s %5f %5f %-4s" % (self.id, self.name, self.midterm, self.final, self.grade)

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(s, student_id):
try:
del s[student_id]
print("student deleted")
except:
print("student ID not valid")
return s
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 storeData1(fn, d):
f = open(fn, "wb") # open file and store
pickle.dump(d, f)
f.close()
print("Goodbye")
print()
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, 7, or 8:
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 = raw_input("Enter your choice, 1, 2, 3, 4, 5, 6, 7, or 8: ")
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, 5, 6, 7, or 8: ")
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", "Grade"))
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=="7":
student_id = input("Enter ID of student to add to course: ")
print("%-4s %-15s %-5s %-5s %-5s" % ("ID", "Name", "Midterm",
"Final", "Grade"))
course=input("Enter course name: ")
l=findcourse(course,totals)
if(l==1):
try:
courses[course]=students[student_id].getStudentData()
except:
print("Invalid entry, please re-enter your choice")
print()
else:
print("Student or course doesnt exist ")
print()
elif opt == "8": # save and exit program
storeData(fn, courses)
storeData(totals) # pickle the dictionary
break

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