Write a complete and
syntactically correct Python program to solve the following
problem:
Write a program for your professor that allows him to keep a record
of the students’ average grade in his class. The program must be
written in accordance with the following specs:
1. The input must be interactive from the keyboard. You will take
input for 12 students.
2. You will input the students’ name and an average grade. The student cannot enter an average below zero or above 100. Your program must raise and handle an exception should this occur.
a. The exception should cause the program to return and get a new grade
3. Write all output to a file named grades.txt
4. Close the output file.
5. Open the file grades.txt for input.
6. Your program will raise and handle an exception if the file is not found.
a. I will
test this aspect by changing the file name and looking for your
exception
code (your exception should cause program to ask for correct file
name).
7. Read all the records from the file and display them.
# Custom exception class class OutOfRange(Exception): pass i = 1 # Variable to keep track of how many students are entered file_write = open('grades.txt', 'w') # Iterate loop 12 times while i <= 12: # Ask user to enter student name name = input('Enter student name ' + str(i) + ': ') # In try-except block, ask user to enter average grade # If its not in range, raise OutOfRange Exception # Catch it in except block and print the error while True: try: average = float(input('Enter average grade: ')) if average < 0 or average > 100: raise OutOfRange break except OutOfRange: print('ERROR: Average must be between 0-100') # Increment i by 1 i += 1 # Write name and grade in file file_write.write('%-15s%-15.2f\n' % (name, average)) # Close the file file_write.close() # Take file name and Open file to read # Do this in a while loop to keep asking user to enter filename till a valid name is entered while True: try: filename = input('Enter file name: ') file_read = open(filename, 'r') break except FileNotFoundError as a: print(a) # Print header print('%-15s%-15s' % ("Name", "Average")) # Read file till the last line # Split line and store it in data # Print name(data[0]) and average(data[1]) for line in file_read.readlines(): data = line.strip().split() print('%-15s%-15.2f' % (data[0], float(data[1]))) # close the file file_read.close()
SCREENSHOT
OUTPUT
Get Answers For Free
Most questions answered within 1 hours.