Skip to main content

Exercises 10.9 Exercises

1.

The following sample file called student_data.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
Data: student_data.txt
Marta 10 15 20 30 23
Ngoc 23 16 19 22
Manjit 8 22 17 14 32 17 24 21 12 9 11 17
Akiko 12 28 21 25 26 10
Kathy 14 32 25 16 29
Abdul 15 19 22 17 20 16 23
Ifedayo 12 18 14 16 23 19
Using the text file student_data.txt write a program that prints out the names of students who have more than six quiz scores.
Solution.
student_file = open("student_data.txt", "r")

for line in student_file:
    items = line.split()
    if len(items[1:]) > 6:
        print(items[0])

student_file.close()

2.

Using the text file student_data.txt (shown in exercise 1), write a program that calculates the average grade for each student, and print out the student’s name along with their average grade.

3.

Using the text file student_data.txt (shown in exercise 1), write a program that calculates the minimum and maximum score for each student. Print out their name as well.
Solution.
student_file = open("student_data.txt", "r")

for line in student_file:
    items = line.split()
    for i in range(len(items[1:])):
        items[i + 1] = int(items[i + 1]) # convert string to integer
        
    print(f"{items[0]}: min {min(items[1:])}, max {max(items[1:])}.")

student_file.close()