Spaghetti code is code that runs correctly but is tangled — one long strand where everything is connected to everything, copy-pasted and hard to follow. You can't change one part without fear of breaking another.
The same lines copy-pasted with tiny changes. Fix one bug and you must fix it everywhere.
One giant flat script with no functions. Nothing has a name; nothing can be reused.
n, a, t, av — you have to decode them. Names should explain themselves.
Bare numbers like 35 or 75 with no name. What do they mean? Give them one.
# student 1
n = "Aarav"; a = 40; b = 55; c = 70 # unclear names
t = a + b + c
av = t / 3 # magic number 3
print("Average: " + str(round(av, 2)))
if av < 35: ... # magic numbers 35, 75
# student 2 ← the SAME block, copy-pasted
n = "Diya"; a = 30; b = 28; c = 33
# ... and again for student 3 (repetition!)
def.print_report(name, m1, m2, m3).PASS_MARK = 35 once, used everywhere.# copy-pasted 3 times
n = "Aarav"
a = 40; b = 55; c = 70
t = a + b + c
av = t / 3
print("Name: " + n)
print("Average: " + str(round(av, 2)))
# ...then ALL of it again, twice
SUBJECTS = 3
def print_report(name, m1, m2, m3):
total = m1 + m2 + m3
average = total / SUBJECTS
print("Name: " + name)
print("Average: " + str(round(average, 2)))
print_report("Aarav", 40, 55, 70)
Refactoring feels risky, but it has a built-in safety net: the program's output is your test. Capture the output before you start. After every small change, run it and compare.
# 1. run the messy version, save the output (your target)
# 2. make ONE small change
# 3. run again — does the output still match?
# same → keep going
# diff → undo that last change, you broke behaviour
"While I'm here, let me fix the formatting to 55.00…" — and now the output differs.
That's a separate task. Today: keep output byte-for-byte identical.
Don't add five layers of helpers for three students. One well-named function is enough. Clean ≠ clever. Stop when it reads clearly.
starter.py prints a report for three students — correctly — but the same block is copy-pasted three times, with magic numbers and one-letter names.
Extract print_report(...), name the constants, call it three times. Follow the # TODO: markers. Output must stay identical.
students/<your-username>/D14_refactor_spaghetti.py. Full brief in lab/module_1_foundations/D14_refactor_spaghetti/problem.md. PR before 12:00. ★ Stretch: drive the reports from a list with a loop.