Report and save
After this: Write the numbers with two decimals, save the report to a file, and read it back.
On this page · 6 sections · 3 checks
Stage 3 prints Class average: 81.16666666666667. The number is right, and nobody wants to read it. A report writes 81.17. Then the report has to be saved, because the moment the program ends, its boxes are gone.
Two decimals
To a number is to write it as text in a chosen shape. Here the shape is two decimals, rounded. In Python an f-string does it: f"{value:.2f}" is the text of value with two decimals. The f before the quotes allows the braces, and :.2f inside them says two decimals.In Java, String.format("%.2f", value) gives the text of value with two decimals. The %.2f is the place where the value goes, and says two decimals.
Step through four ways of printing the same number:
valueitself prints as 81.16666666666667.roundfrom "Input, files and the standard library" gives a number, 81.17. It is still a number, and rounding 78.5 this way would stay 78.5, not 78.50.- The format gives text,
81.17, with exactly two decimals. - The same format on 78.5 gives
78.50: the text always has two decimals, which lines a report up.
value = 81.16666666666667print(value)print(round(value, 2))print(f"{value:.2f}")print(f"{78.5:.2f}")run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The report uses the format in two places: the line for each student, which is the __str__toString method, and the class average line.
The report as a list of lines
A function, report_linesreportLines, builds the report as a list of strings: one line per student, then the top student, then the class average. It calls the stage 3 functions and formats what they give back. Building the lines first and writing them afterwards keeps the two jobs apart, so that the same lines could also be printed or sent somewhere else.
Saving the report
Writing the lines to a file is the pattern from "Input, files and the standard library": open report.txt for writing, write each line with its line end, let the withtry line close the file, then open the file again and read it back, so that the program shows what really landed in it.
lines = ["Ana: 78.50", "Top student: Cy"]with open("report.txt", "w") as f: for line in lines: f.write(line + "\n")with open("report.txt") as f: saved = f.readlines()for line in saved: print(line.strip())run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The finished program
Here is the whole program, stage 4. Read it from the top: the class, then four functions, then the lines that run them.
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): return sum(self.marks) / len(self.marks)
def __str__(self): return f"{self.name}: {self.average():.2f}"
def load(filename): students = [] with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") marks = [int(parts[1]), int(parts[2])] students.append(Student(parts[0], marks)) except ValueError: print("Skipping bad line: " + line.strip()) return students
def top_student(students): best = students[0] for s in students: if s.average() > best.average(): best = s return best
def class_average(students): total = 0 for s in students: total = total + s.average() return total / len(students)
def report_lines(students): lines = [] for s in students: lines.append(str(s)) lines.append("Top student: " + top_student(students).name) lines.append(f"Class average: {class_average(students):.2f}") return lines
students = load("marks.txt")with open("report.txt", "w") as f: for line in report_lines(students): f.write(line + "\n")with open("report.txt") as f: saved = f.readlines()for line in saved: print(line.strip())Ana: 78.50 Ben: 75.00 Cy: 90.00 Top student: Cy Class average: 81.17
import java.io.IOException;import java.io.PrintWriter;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class Student { String name; List<Integer> marks;
Student(String name, List<Integer> marks) { this.name = name; this.marks = marks; }
double average() { int total = 0; for (int m : marks) { total = total + m; } return (double) total / marks.size(); }
public String toString() { return name + ": " + String.format("%.2f", average()); }}
public class Main { static List<Student> load(String filename) throws IOException { List<Student> students = new ArrayList<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); List<Integer> marks = List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2])); students.add(new Student(parts[0], marks)); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return students; }
static Student topStudent(List<Student> students) { Student best = students.get(0); for (Student s : students) { if (s.average() > best.average()) { best = s; } } return best; }
static double classAverage(List<Student> students) { double total = 0; for (Student s : students) { total = total + s.average(); } return total / students.size(); }
static List<String> reportLines(List<Student> students) { List<String> lines = new ArrayList<>(); for (Student s : students) { lines.add(s.toString()); } lines.add("Top student: " + topStudent(students).name); lines.add("Class average: " + String.format("%.2f", classAverage(students))); return lines; }
public static void main(String[] args) throws IOException { List<Student> students = load("marks.txt"); try (PrintWriter out = new PrintWriter("report.txt")) { for (String line : reportLines(students)) { out.println(line); } } List<String> saved = Files.readAllLines(Path.of("report.txt")); for (String line : saved) { System.out.println(line); } }}Ana: 78.50 Ben: 75.00 Cy: 90.00 Top student: Cy Class average: 81.17
The running part is seven lines at the end: load the students, write the report lines to the file, read the file back, print it. Everything above those lines is a tool that waits to be called.
Change both .2f to .1f and run it again: one decimal everywhere.
Check yourself
What does this program print?
print(f"{7.0 / 4:.2f}")print(f"{2.0 / 3:.2f}")print(f"{78.5:.2f}")public class Main { public static void main(String[] args) { System.out.println(String.format("%.2f", 7.0 / 4)); System.out.println(String.format("%.2f", 2.0 / 3)); System.out.println(String.format("%.2f", 78.5)); }}Complete the missing line so that each line of the report goes into the file, each on its own line. The program then reads the file back and prints Ana: 78.50 and Top student: Cy.
lines = ["Ana: 78.50", "Top student: Cy"]with open("report.txt", "w") as f: for line in lines: ____________________ # ← put this line into the file, with its line endwith open("report.txt") as f: saved = f.readlines()for line in saved: print(line.strip())import java.io.IOException;import java.io.PrintWriter;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class Main { public static void main(String[] args) throws IOException { List<String> lines = List.of("Ana: 78.50", "Top student: Cy"); try (PrintWriter out = new PrintWriter("report.txt")) { for (String line : lines) { ____________________ // ← put this line into the file, with its line end } } List<String> saved = Files.readAllLines(Path.of("report.txt")); for (String line : saved) { System.out.println(line); } }}You run the finished program twice. The report has five lines. After the second run, what does report.txt hold?
Honesty notes
- Write a number with two decimals as text (an f-string with :.2f in Python, String.format with %.2f in Java), and say that rounding is for display.
- Build the report as a list of lines, one per student and two summary lines, in a function of its own.
- Write the lines to report.txt, let the with line (the try line in Java) close the file, and read the file back to check it.
- Read the finished program from top to bottom: the class, four functions, and seven lines that run them.