Week 12 Homework: Understanding, Testing, and Debugging Programs That Process Files

Reminder: You are not being graded on writing Python syntax. You are being graded on whether you can read, trace, test, and fix code — the same skills you'd use working alongside an AI coding agent. Do not use an AI agent to solve this homework; you are the one being assessed on these skills this time.


Part 1 — Understanding and Predicting Output

Program: grade_report.py

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def main():
    filename: str = "scores.txt"
    total: int = 0
    count: int = 0
    highest: int = None
    lowest: int = None

    infile = open(filename, "r")

    print("Student Grade Report")
    print("---------------------")

    for line in infile:
        line = line.strip()
        if line != "":
	        parts: list[str] = line.split(",")
	        name: str = parts[0]
	        score: int = int(parts[1])
	
	        letter: str = get_letter_grade(score)
	        print(f"{name}: {score} ({letter})")
	
	        total += score
	        count += 1
	
	        if highest is None or score > highest:
	            highest = score
	        if lowest is None or score < lowest:
	            lowest = score

    infile.close()

    if count > 0:
        average = total / count
        print("---------------------")
        print(f"Number of students: {count}")
        print(f"Class average: {average:.2f}")
        print(f"Highest score: {highest}")
        print(f"Lowest score: {lowest}")
    else:
        print("No student data found.")

main()

Input File 1 — scores1.txt

Alice,95
Ben,82
Carla,71
Diego,68
Elena,55
Farid,88

Input File 2 — scores2.txt

Grace,90

Hank,80
Isla,70
Jamal,60

(Note: line 2 is intentionally blank.)

Input File 3 — scores3.txt

(this file is completely empty — 0 bytes)

Your Task

For each of the three input files above:

  1. Trace through grade_report.py by hand, line by line, as if you were the computer.
  2. Write out the exact console output you predict the program will produce, including spacing and punctuation.
  3. In 1–2 sentences, explain why that file was included — what specific behavior of the program does it test? (Hint: think about boundaries, blank lines, and missing data.)

Submit your predictions in a table like this for each file:

Line of OutputYour Predicted Text
1
2
...

Part 2 — Creating Test Files

Program: weather_log.py

def classify_temperature(temp):
    if temp >= 85:
        return "Hot"
    elif temp >= 60:
        return "Mild"
    else:
        return "Cold"

def main():
    filename: str = "weather.txt"
    infile = open(filename, "r")

    temps: list[int] = []

    print("Weather Log Analysis")
    print("---------------------")

    for line in infile:
        line = line.strip()
        if line != "":
	        temp: int = int(line)
	        temps.append(temp)
	        category: str = classify_temperature(temp)
	        print(f"{temp} degrees - {category}")

    infile.close()

    print("---------------------")
    if len(temps) > 0:
        print(f"Days recorded: {len(temps)}")
        print(f"Average temperature: {sum(temps)/len(temps):.1f}")
        print(f"Warmest day: {max(temps)}")
        print(f"Coldest day: {min(temps)}")
    else:
        print("No temperature data available.")

main()

Your Task

This program expects a file named weather.txt containing one temperature (a whole number) per line.

Design and submit three separate input files — weather_test1.txt, weather_test2.txt, weather_test3.txt — that together test the program thoroughly, including at least one edge case it might not handle gracefully.

For each file you create, fill in this table:

File NameWhat It ContainsWhat It's Meant to TestExpected Behavior
weather_test1.txt
weather_test2.txt
weather_test3.txt

Things to think about as you design your files (you do not need to use all of these — pick what makes sense):

Submit the three .txt files along with your completed table.


Part 3 — Debugging

Program: sales_report.py

Intended behavior (the spec):

The code below does not correctly match this spec. It contains four bugs in addition to not having explicit typing.

def main():
    filename = "sales.txt"
    infile = open(filename, "r")

    grand_total = 0

    print("Sales Report")
    print("-------------")

    for line in infile:
        line = line.strip()
        if line != "":
	        parts = line.split(",")
	        item = parts[0]
	        price = parts[1]
	        quantity = int(parts[2])
	
	        subtotal = price * quantity
	        grand_total = subtotal
	
	        print(f"{item}: ${subtotal}")

    print("-------------")
    print(f"Grand Total: ${grand_total}")

    if grand_total > 100:
        discount = grand_total * 0.10
        final_total = grand_total - discount
        print(f"Discount applied: ${discount:.2f}")
        print(f"Final Total: ${final_total:.2f}")

main()

Input File 1 — sales1.txt

Laptop,899.99,1
Mouse,19.99,2
Keyboard,49.99,1

Input File 2 — sales2.txt

Notebook,5.00,10
Pen,2.50,20

Your Task

  1. Run (or trace by hand) sales_report.py against both input files.
  2. Compare what actually happens to what the spec says should happen.
  3. Identify all four bugs. For each one, write:
    • The line(s) of code where the bug is
    • What the bug causes to go wrong (be specific — reference one of the input files as evidence)
    • The corrected line(s) of code
  4. Add explicit typing for the entire program.
  5. Submit a corrected version of sales_report.py that matches the spec exactly.

Hint: One bug won't show up as an obvious crash or wrong number on the first file alone — you may need to compare behavior across both input files to catch it. Pay close attention to what happens when the grand total lands exactly on a boundary.


Submission Checklist