Help with Classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jesse Dye
    New Member
    • Nov 2011
    • 1

    #1

    Help with Classes

    Hi I am trying to introduce a class into the code below. The code opens a file with comma separated values (e.g: John, 100). The program gives you a menu 1 to read the file, 2 adds a new student to the file. And 3 calculates the mean and range for all the grades. I am stuck at number 3 which calculates the mean and range for the numbers from the text file.

    Below is the Code:


    Code:
    import math
    
    def main():
        menu = eval(input("Select 1 to get grades, 2 to add students, or 3"))
        if (menu ==1):
            #print("test")
    
            fileName = input("Enter filename: ")
            infile = open(fileName,"r")
            data = infile.read()
            print(data)
    
        if (menu ==2):
            #print("test3")
    
    
            filename1 = input("what is the file name?")
    
            file1 = open(filename1, "a")
            file1.close()
    
            studentName =input("what is the student name?")
            studentGrade =input("What is the student grade?")
            file1 = open(filename1, "a")
            file1.write(studentName + "," +studentGrade + "\n")
            file1.close()
    
    
    
        if (menu ==3):
            #print("test3")
    
            filename2 = input("what is the file name?")
            infile = open(filename2,"r")
            sum = 0.0
            count = 0
            for lines in infile:
                name, grade = lines.split(",")
                numbers = grade
                print(numbers)
    
        else:
            print ("Please enter a valid number")
    
    main()
    Last edited by bvdet; Nov 16 '11, 10:21 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The range would be the highest and lowest grades. The mean would be the grade in the middle. You would need to type cast the grade into an integer and compile the grades into a list to evaluate.

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      Under option #2 you open and close the file twice. Once is enough.
      Code:
        if (menu ==2):
               #print("test3")
       
       
               filename1 = input("what is the file name?")
       
               file1 = open(filename1, "a")
      ##         file1.close()      ## close after writing
       
               studentName =input("what is the student name?")
               studentGrade =input("What is the student grade?")
      ##         file1 = open(filename1, "a")     ## already open
               file1.write(studentName + "," +studentGrade + "\n")
               file1.close()

      Comment

      Working...