Projects · 1 / 19 Theory

From a problem to a program

You already know the tools: variables, conditions, loops, functions, classes, files, exceptions... A project consists of combining them to solve a complete problem. The difficulty is no longer the syntax, but organising the work.

A five-step method

  • Understand the problem: what goes in, what comes out and which odd cases may appear (empty, repeated, invalid value).
  • Choose the data: which structure best represents the information (list, dictionary, set, class, dataclass...).
  • Split into functions: each does one thing and has a clear name.
  • Write a main loop that reads the commands or data and calls the functions.
  • Test with small examples, starting with the simplest case, and then with the edge cases.

Choosing the data structure

I need to...Structure
Look up a value by its nameDictionary
Keep an order and allow duplicatesList
Know whether something already appearedSet
Count how many times each thing appearsCounter
Group several fields of one objectClass or dataclass
A closed set of optionsEnum

An example: for a contact book (Contact book) you search by name, so a dictionary name -> phone is the natural choice. To count the levels of a log (Log analyzer) you would use a Counter.

The command loop pattern

Many small programs follow the same outline: read a command, decide what to do and repeat.

n = int(input())
for _ in range(n):
    parts = input().split()
    command = parts[0]
    if command == "greet":
        print("Hello,", parts[1])
    elif command == "add":
        print(int(parts[1]) + int(parts[2]))

With the input 2, greet Ana and add 3 4, it shows Hello, Ana and 7. The projects Inventory control and Contact book use this pattern with richer commands.

Input and output with a format

Almost all the problems in this course fix the exact format of the input and the output. Read it carefully: an extra space or a changed capital letter makes the output different. Some useful techniques:

  • line.split() splits on spaces; line.split(",") on commas.
  • F-strings give format: f"{x:.2f}" shows two decimals and f"{n:02d}" pads with zeros.
  • json.dumps(data, ensure_ascii=False) writes a dictionary or list as JSON.
  • sorted(d.items(), key=lambda p: (-p[1], p[0])) sorts from highest to lowest value and, on a tie, by key.
values = {"b": 2, "a": 2, "c": 5}
for key, v in sorted(values.items(), key=lambda p: (-p[1], p[0])):
    print(f"{key}: {v}")
# c: 5
# a: 2
# b: 2

Decide where each thing goes

Before writing a line, sketch on paper the functions you need, what each one receives and what it returns. If a function needs more than three or four related parameters, you probably want a class. If a function does two different things, split it in two.