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,88Input 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:
- Trace through
grade_report.pyby hand, line by line, as if you were the computer. - Write out the exact console output you predict the program will produce, including spacing and punctuation.
- 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 Output | Your 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 Name | What It Contains | What It's Meant to Test | Expected 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):
- What happens exactly at the boundary values in
classify_temperature(85 and 60)? - What happens if the file has only one line?
- What happens if the file is empty?
- What happens with a negative temperature?
- What happens if a line in the file isn't a valid whole number?
Submit the three .txt files along with your completed table.
Part 3 — Debugging
Program: sales_report.py
Intended behavior (the spec):
- The program reads a file called
sales.txt, where each line is formatteditem,price,quantity(price is a dollar amount like19.99). - For each line, it should print the item name and its subtotal (
price * quantity). - It should keep a running grand total across all items.
- After processing every line, it prints the grand total.
- If the grand total is $100.00 or more, it should apply a 10% discount and print the discount amount and the final discounted total.
- The file should be properly closed when the program is finished with it.
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,1Input File 2 — sales2.txt
Notebook,5.00,10
Pen,2.50,20Your Task
- Run (or trace by hand)
sales_report.pyagainst both input files. - Compare what actually happens to what the spec says should happen.
- 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
- Add explicit typing for the entire program.
- Submit a corrected version of
sales_report.pythat 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
-
Part 1: Predicted output for all three
scoresfiles + explanation of what each file tests -
Part 2: Three original input files (
weather_test1.txt,weather_test2.txt,weather_test3.txt) + completed test-purpose table - Part 3: List of all four bugs (location, explanation, fix)
- Homework12.ipynb containing the corrected sales_report.py code with explicit typing