Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 14 of 15

Code organization

Structuring code so it stays manageable: separating logic from input and output, configuration and constants at the top, a main() entry point, layering storage, services and presentation, and splitting into modules.

Beginner 10 min read·Lesson 292 of 306 in Python Programming

Learning objectives

  • Separate pure logic from input and output
  • Organise a script with constants, functions and main()
  • Layer an application into storage, service and presentation

Definition

Code organization is how a program's functions, classes and files are arranged. Well-organised code separates concerns — calculation, storage, input/output and configuration — so each part can be understood, tested and changed on its own.

Introduction

A 400-line script that reads input, calculates and prints all mixed together works — until you need to change one part. Organisation makes change cheap.

Why it matters

Organised code is easier to test (logic without I/O), reuse (import functions) and extend (replace one layer without touching others).

Detailed explanation

Separate concerns: functions that compute results shouldn't also read input or print output. Pure functions (same input, same output, no side effects) are easiest to test.

A common script layout: imports, constants and configuration, function and class definitions, then a main() function called under if __name__ == "__main__":.

Group related functions; when a file grows large, move groups into modules (storage.py, pricing.py, cli.py).

Layered design: a storage layer saves and loads data, a service layer applies business rules, and a presentation layer handles input and output.

Each layer talks only to the one below it through a small interface, so you can swap file storage for a database without touching the user interface.

Keep configuration (file paths, rates, limits) in one place rather than scattered literals.

Avoid global mutable state; pass data to functions explicitly.

Organise tests to mirror the code: tests/test_pricing.py for pricing.py.

Syntax

Python
TAX_RATE = 0.18
def price_with_tax(price): # logic
return round(price * (1 + TAX_RATE), 2)
def main(): # input/output
price = float(input("Price: "))
print(price_with_tax(price))
if __name__ == "__main__":
main()
  • Separate logic from I/O.
  • Constants at the top, main() at the bottom.
  • Layers with small interfaces.

Code examples

Logic separate from output

Python
def parse_scores(text):
return [int(x) for x in text.split(",")]
def summarize(scores):
return {"count": len(scores), "best": max(scores), "average": sum(scores) / len(scores)}
def format_summary(s):
return f"{s['count']} scores, best {s['best']}, average {s['average']:.1f}"
def main(text="72,91,85"):
print(format_summary(summarize(parse_scores(text))))
main()
Output
3 scores, best 91, average 82.7

A conventional script layout

Python
TAX_RATE = 0.18
def price_with_tax(price):
return round(price * (1 + TAX_RATE), 2)
def main():
print(price_with_tax(100), price_with_tax(59.99))
if __name__ == "__main__":
main()
Output
118.0 70.79

More examples

Storage, service and presentation layers

Python
class MemoryRepo:
def __init__(self):
self._items = {}
self._next_id = 1
def add(self, todo):
todo["id"] = self._next_id
self._items[self._next_id] = todo
self._next_id += 1
return todo
def get(self, todo_id):
return self._items[todo_id]
def all(self):
return list(self._items.values())
class TodoService:
def __init__(self, repo):
self.repo = repo
def add(self, title):
title = title.strip()
if not title:
raise ValueError("title cannot be empty")
return self.repo.add({"title": title, "done": False})
def complete(self, todo_id):
self.repo.get(todo_id)["done"] = True
def pending(self):
return [t for t in self.repo.all() if not t["done"]]
def render(todos):
return "\n".join(f"[{t['id']}] {t['title']}" for t in todos) or "nothing to do"
service = TodoService(MemoryRepo())
service.add("write tests")
service.add("fix bug")
service.complete(1)
print(render(service.pending()))
try:
service.add(" ")
except ValueError as e:
print(e)
Output
[2] fix bug
title cannot be empty

Step-by-step explanation

  • MemoryRepo only stores and retrieves; it knows nothing about rules or display.
  • TodoService enforces the rules (no empty titles) and uses the repository through three methods.
  • render turns data into text; a file- or database-backed repository could replace MemoryRepo without changing the other layers.

Expected output

Running “Storage, service and presentation layers” prints exactly:

TextOutput
[2] fix bug
title cannot be empty

Practical applications

  • Web applications with models, services and views.
  • Command-line tools whose logic is reused by a web interface.

Best practices

  • Keep calculations pure.
  • Use main() and the __main__ guard.
  • Split large files into focused modules.

Common mistakes

Logic tangled with I/O

Avoid

def total():
n = int(input())
...
print(result)

Prefer

def total(values):
return sum(values)
print(total(read_values()))

Functions that read and print can't be tested or reused easily.

Important notes

  • The Modules and Packages module covers turning these layers into separate files and packages.

Key takeaways

  • Separate logic, storage, I/O and configuration.
  • Use a consistent script layout with main().
  • Layers communicate through small interfaces.

Try it yourself

  1. 1
    Refactor a script that mixes input, calculation and printing into separate functions.
  2. 2
    Add a FileRepo to the todo example that saves to JSON, without changing TodoService.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Debugging, Testing and Best Practices” module. Answers and explanations are revealed after you submit.

  • AdvancedWhy shouldn't assert be used to validate user input?
  • AdvancedWhat is printed?
  • AdvancedWhere should you usually start reading a Python traceback?
Practise this module