The last make task of the chapter, and the one where the program writes a whole file in a loop.
A teacher needs a program to quickly enter a list of students and their test scores, saving them all into a single text file. The teacher does not know exactly how many students took the test, so the program has to keep going until the teacher says they are finished.
Write a program that:
results.txt in write mode ("w"),STOP means that
there are no more students,while) loop that keeps going as long as the
name is not STOP,int(),"\n") at the end,Results saved.The tests also check your code: use int() to read the score.
The question for a name, asked before the loop and again at the end of every repetition:
Enter student name or STOP to finish
The question for a score, asked once for every student:
Enter test score
And the last line, once the file has been closed:
Results saved
results.txt holds one line per student, in the order they were entered, where
NAME is the name and SCORE the score:
NAME SCORE
Every line ends with a "\n", the last one included. Anything the file held
before the program ran is replaced. If the teacher types STOP straight away,
the file ends up empty.
Input:
Amira
72
Ben
45
Chloe
90
STOP
Output:
Enter student name or STOP to finish
Enter test score
Enter student name or STOP to finish
Enter test score
Enter student name or STOP to finish
Enter test score
Enter student name or STOP to finish
Results saved
results.txt afterwards:
Amira 72
Ben 45
Chloe 90
Ask each question with its own print, and read the answer with a bare
input() on the next line, rather than passing the question to input(...).
The questions are part of the output that is checked here, so their spelling,
capital letters and punctuation count. So do the lines in the file.
Make sure that you check for the following things:
"w" mode inside the loop and every student wipes the one before.STOP is compared exactly, in capital letters: name != "STOP".str() before it is joined onto the name, and every
line ends with "\n".Results saved is not indented, so it is printed once, after the loop.