I stuck with one problem with my programming exercise thst sounds like:
- Write a simple program to first prompt the user to enter the filename of the text file that they wish to open. The program should then open the text file, read the contents of the file, and store this in a suitable Python data structure. Make sure you include a suitable exception handling (try ... except) structure that will inform the user if there is a problem loading the file and allows the user to enter an alternative filename if there is a problem.
- Once the data is successfully loaded, print out the data in a neatly formatted manner (see an example output below). 3). Calculate the average mark for each student and print these out with the data in task 3. Then also calculate the average mark for the class and print this out at the end.
Here is how the output shoul looks like:
Enter a filename: Student Marks.txt
Student Marks
Jean Paul Alarie:
Marks: 56.0, Average: 56.0
Juan Manuel Bienvenida:
Marks: 72.6, 12.0, Average: 42.3
Janet Brimfield:
Marks: 66.3, 71.0, Average: 68.65
Helen Jane Burnett:
Marks: 54.0, Average: 54.0
Bernard Galpin:
Marks: 45.0, 66.2, 32.0, Average: 47.73
…
Average: 54.26
I know how to allow the user to enter a file and output its data to the screen, but I don't know how to make the output as shown in the sample and how to use operations on numbers in this case.
If you can help me and tell me how to solve it, I will be very grateful. Here is a sample of the code I have
while True:
try:
fname=input('Enter the file name: ')
infile = open (fname, "r")
data = infile.read()
infile.close()
print(data)
print()
count = 0
total = 0
i = 0
while i < len(data):
print(data[i], ":", data [i+1])
count = count +1
total = total + float (data [i+1])
i=i+2
print("avarage:", total/count)
except:
print("There was an Error")
continue
And here is the output with an error:
Enter the file name: sm.txt
Student Marks
Jean Paul Alarie 56
Juan Manuel Bienvenida 72.6 12
Janet Brimfield 66.3 71
Helen Jane Burnett 54
Bernard Galpin 45 66.2 32
Alexander Adam Janssen 41 21
Struan Kilgour 79 82.5 45.5
Pierre Antoine Lajoie 56.2 45.5
Hamish McDonald 66.5 91
Shakeel Mirza 12
Sidney Rickard 88 78 84.4
Sharlene Urry 54.5
Karl James Richard White 62 59.5 41.2 66
S : t
Traceback (most recent call last):
File "C:/Users/Elf/Desktop/Essex lab/programming/spring term/week 20/ooooo.py", line 17, in <module>
total = total + float (data [i+1])
ValueError: could not convert string to float: 't'