Projects · 3 / 19 Theory

Structure and good practices

When a program grows, the way you organise it matters as much as what it does. These practices save you time and errors, and make it understandable for other people (and for you six months from now).

A skeleton for any program

import json

LIMIT = 100           # constants at the top, in capitals

def double(x):
    """Return twice x."""
    return x * 2

def main():
    print(double(21))

if __name__ == "__main__":
    main()   # 42

if __name__ == "__main__" makes main() run only when you launch the file directly, not when another program imports it. This way the same file works as a program and as a reusable module. In the exercise solutions it is left out to keep them short.

Names that explain

BadBetter
d, x2, lstprices, total, names
proc()compute_total()
flaghas_error, is_valid
l = [] (looks like 1)lines = []

Use lowercase names with underscores for variables and functions, CamelCase for classes and CAPITALS for constants. A good name makes a comment unnecessary.

Small functions with a single task

A function should fit on one screen and be describable in one sentence without using "and". If you compute and display, separate both: the part that computes can be tested with assert.

def average(values):
    return sum(values) / len(values)

def show_average(values):
    print(f"Average: {average(values):.2f}")

assert average([2, 4, 6]) == 4
show_average([2, 4, 7])   # Average: 4.33

Handle errors on purpose

  • Validate what comes from outside (user input, files) and not what you control.
  • Catch specific exceptions (ValueError, KeyError), never a bare except: that hides failures.
  • Create your own exceptions when an error has meaning in your domain, like InsufficientStock in Inventory control.
  • Close files with with.

Checklist before calling a project finished

  • Does it work with the simplest case and with empty input?
  • Have I tested the boundary values (0, one, the maximum)?
  • Is there repeated code that could be a function?
  • Can the names be understood without reading the code?
  • Have I removed the debugging print calls?
  • Could someone else run it by following my instructions?

What now?

With the projects in this lesson you have used almost the whole course: dictionaries, regular expressions, dataclasses, enumerations, exceptions, generators, csv, json and tests. To keep growing:

  • Read the official documentation of Python and the standard library: it is the best source and very well written.
  • Learn to install packages with pip and to use virtual environments (python -m venv).
  • Learn git to keep the history of your projects.
  • And above all, create your own projects: an application for something you care about will teach you more than any exercise. Start small and expand.

You learn programming by programming. Good luck!