Calculate the grade average of the class

Try me

Open In ColabBinder

We have a text file with the marks of the class students. Each row contains information for a different student. Each row has the following information: identifier,username,note each field separated by a comma (CSV). Fields cannot have commas internally, because it would be considered a field separation.

For example,

1,frasalca,6.5
2,romelco,9.1
3,beaguma,7.4
4,pacosa,8.6

To create a text file, press the + button and select Text file. Write the content and save it with a name, for example, marks.csv.

In Python, in order to read a file it is necessary to open it first (and when we finish, it ha to be closed). You can use:

f = open("marks.csv")

To open the file, and:

f.close()

To close it.

Once the file is opened with the open() function and before closing it, it can be read line by line with the f.readline() function. For example:

`line = f.readline()

will assign the variable line with the first line of the file.

If the line variable is not empty, it means that we have not reached the end of the file yet. Therefore, to iterate through the lines of the file we can use while. You cannot forget to reread the next line of the file inside the loop so as not to generate an infinite loop. For example,

line = f.readline()
while line:
    print(line)
    line = f.readline()

This code will read line by line from the file and print it on the screen. When there are no more lines left, the loop will end because the while line: condition will be false.

Once you have the line of text, you can separate each of the columns and obtain an array using the split() function. You have to pass the separator as a parameter of the function. For example, text = "1 frasalca 6.5" list = text.split()

This code will make the variable list have an array with the values: ["1","frasalca","6.5"]. Accessing the mark can be done with list[2]. If you want to use any of these values as an integer or decimal number, you have to convert them with the int() ord float() functions respectively.

So far, with all the previous explanation, develop the following program:

A program that reads a text file with the students’ data (identifier, user name, grade) on each line, calculates the average among all the students’ grades and prints it on the screen. It must also print on screen for each student whether they have passed or not (print student name and PASS or NOT PASS). Students need a grade of 5 or more to pass.

In order to be used by your program, a file marks.csv must first be generated with the information of at least 5 students (made-up).

The following flow chart diagram illustrates the algorithm used to calculate the average grade:

student marks

[7]:
f = open("marks.csv")
total = 0
count = 0
line = f.readline()
while line:
    cols = line.split(",")
    name = cols[1]
    mark = float(cols[2])
    if mark >= 5:
        status = "PASSED"
    else:
        status = "NOT PASSED"
    print(f"{name}: {status}")
    total = total + mark
    count = count + 1
    line = f.readline()
f.close()

average = total/count
print(f"Average grade: {average}")
frasalca: PASSED
romelco: PASSED
beaguma: PASSED
pacosa: PASSED
raumomo: NOT PASSED
lapasa: NOT PASSED
vicoca: PASSED
Average grade: 7.114285714285714

We can modify the solution to use the with statement, which will automatically close the file when the block ends. This is the recommended way to open files in Python.

[10]:
with open("marks.csv") as f:
    total = 0
    count = 0
    line = f.readline()
    while line:
        cols = line.split(",")
        status = "PASSED" if float(cols[2]) >= 5 else "NOT PASSED"
        print(f"{cols[1]}: {status}")
        total = total + float(cols[2])
        count += 1
        line = f.readline()

    average = total / count
    print(f"Average grade: {average:.2f}")
frasalca: PASSED
romelco: PASSED
beaguma: PASSED
pacosa: PASSED
raumomo: NOT PASSED
lapasa: NOT PASSED
vicoca: PASSED
Average grade: 7.11

Analysis questions

  1. File Input: What file format does the program expect the grades to be stored in? Describe the structure of this file.

  2. Reading Process: How does the program read through each line of the file? Why is a while loop used for this process?

  3. Data Parsing: How does the program extract individual pieces of data from each line? Why does it use the split(“,”) function?

  4. Grade Check: The program determines whether a student has passed or not based on their grade. How does the program decide this, and what grade threshold is used?

  5. Accumulators and Average Calculation: What are the roles of the variables total and count in the program? How are they updated as the program reads through the file? How does the program compute the average grade of all students? What happens if the file has no grade records?

  6. Extensions: How would you modify the program to also display the highest and lowest grades? What changes would be needed? How would you modify the program to store the grades and statistics in separate files? What changes would be needed?