Skip to content
FORGENO ADS GAMESUnlock all $8

Python Programming · Unit 8 of 8

Unit 8: Mini project and Python at work

Plan a program, build and test a stock-report tool step by step, see Python at work in scripts, data and web back ends, use venv and pip, and plan your next credential.

Opens the first lesson of this unit in Python Programming. Every lesson is open from the start.

Lesson 1: Planning a program

Goal: Turn a request into a plan: clarify the requirements, write examples, split the work into functions and choose the data structures.

At work, tasks rarely arrive as exercises. They arrive as a message: "Can you make something that tells us which products are running low? The stock export is attached." The most common mistake is to start typing straight away. Ten minutes of planning saves hours of rewriting.

  1. Clarify the goal. Who reads the result, and what decision does it support? Here: the shop manager, deciding what to reorder.
  2. Look at the real data. Open the export. Note the columns and anything messy: missing values, words where numbers should be, extra spaces.
  3. Write examples of input and expected output before writing code. They become your first tests.
  4. Split the work into small functions with one job each, and write their names and docstrings first.
  5. Choose data structures. A class for one item? A dictionary for groups? A list of records?
  6. Ask about edge cases: what should happen with a broken row, an empty file or a tie?

This decomposition of a problem into small functions is the core skill of programming. Each function should do one thing you can describe in a sentence, take what it needs as parameters, and return a result rather than print it. Small functions are easy to test, easy to reuse and easy for a colleague to review.

# stock_report.py: the plan, written before the code
# Input:  CSV text "name,qty,price" with some broken rows
# Output: a short report for the manager, listing problems found

def parse_row(row):
    """[name, qty, price] strings -> (name, qty, price), or raise ValueError."""

class Item:
    """One product: name, qty, price; knows its value() and whether is_low()."""

def load_items(csv_text):
    """Read the CSV -> (items, errors); never crash on a bad row."""

def summarize(items, threshold=5):
    """Totals and the sorted names of low-stock items, as a dict."""

def report(csv_text):
    """The whole report as one string."""

Worked example: the plan for the stock report

  1. Each function has one job: parse a row, model an item, load the file, do the arithmetic, format the text.
  2. Data flows in one direction: text → rows → Items → summary → report.
  3. Bad rows become messages in an errors list, so one broken line cannot stop the report.
  4. Separating summarize (numbers) from report (text) means the arithmetic can be tested without caring about layout.

With the plan written, each function is a small, testable exercise, which is exactly how the next lesson builds it.

Writing the plan as function stubs with docstrings, before any bodies, is a professional habit: it forces clear thinking, makes the work easy to share out in a team, and turns into documentation for free. Python requires a body, so while sketching you can put ... or pass inside each function.

Hands-on lab in the room: Mini project: stock report. Mini project, step 1: write and test parse_row, the smallest piece.

Requirements
What a program must do, for whom, and with what input and output.
Decomposition
Breaking a problem into smaller parts, usually functions, each with one clear job.
Function stub
A function written with its name, parameters and docstring but no real body yet.
Edge case (in planning)
An unusual situation, such as an empty file or a broken row, that the plan must decide how to handle.

Remember: Before coding: clarify who it is for, read the real data, write example inputs and outputs, and sketch the functions with docstrings.

Lesson 2: Building and testing the mini project

Goal: Build a program step by step, running and testing each piece, and finish it as a script with a __main__ guard.

Build in small steps and run after every step. Write one function, test it with a couple of examples, and only then move on. When something breaks, you know it is in the last few lines you wrote, which makes bugs cheap. The mini project lab below follows exactly this rhythm: five steps, each with its own checks.

The mini project, step by step
StepYou writeYou test
1parse_row(row)a good row, extra spaces, each kind of bad row
2class Itemvalue(), is_low() with and without a threshold, repr()
3load_items(csv_text)the sample file, blank lines, a file with only a header
4summarize(items)the totals, a custom threshold, no items
5report(csv_text)the exact text for the sample, and for a clean file

Two techniques make the loader robust. Re-raising with a clearer message: parse_row catches Python's ValueError from int("ten") and raises a new one saying bad quantity: 'ten', which a manager can understand. Collecting errors instead of stopping: load_items wraps each row in try/except and appends f"line {n}: {e}" to a list, so the report can list every problem with its line number.

def report(csv_text):
    """The full stock report for some CSV text, as one string."""
    ...

if __name__ == "__main__":
    with open("stock.csv", encoding="utf-8") as f:   # on your own computer
        print(report(f.read()))

Worked example: finishing as a script

  1. Every module has a __name__. When you run a file directly, Python sets it to "__main__".
  2. When another file imports it (for example a test file), __name__ is the module's own name instead, so the block does not run.
  3. So the same file works as a script (python stock_report.py) and as a library other code and tests can import without side effects.
  4. In the lab, the block prints the report for the sample text instead of reading a file.

The if __name__ == "__main__": guard is in almost every real Python script. Expect to be asked what it does.

When it works, refactor: improve the code without changing what it does. Rename unclear variables, remove duplication, split any function that grew too long, then rerun the checks to prove nothing changed. Tests are what make refactoring safe. Finally, read your code as a reviewer would: would a teammate understand it without asking you?

Hands-on lab in the room: Mini project: stock report. Build the whole tool: five steps, each with hidden checks, hints and a worked solution. Your code from each step is carried into the next.

Incremental development
Building a program in small steps, running and testing after each one.
__name__ == "__main__"
A check that is true only when a file is run directly, not imported; used to start a script.
Refactor
To improve code's structure without changing what it does, with tests proving nothing broke.
Code review
A teammate reading your changes before they are accepted, to catch bugs and improve clarity.

Remember: Write a little, run it, test it, repeat. Collect errors instead of crashing. End scripts with if __name__ == "__main__":

Lesson 3: Python at work

Goal: Describe how Python is used for scripts and automation, data work and web back ends, and what junior developers do day to day.

Python is used in very different jobs, but they share the core you have learned: types, collections, functions, errors, files and testing. Knowing the landscape helps you choose where to aim and what to learn next.

Where Python is used
AreaWhat Python does thereTools you will hear about
Scripts and automationrename and sort files, generate reports, move data between systems, run nightly jobspathlib, argparse, csv, json, scheduled tasks
Data analysisclean and summarise large datasets, charts, notebookspandas, NumPy, Jupyter notebooks, SQL
Web back endsthe server side of websites and APIs: receive a request, run logic, return HTML or JSONDjango, Flask, FastAPI, databases
Testing and DevOpsautomated tests, deployment scripts, infrastructure toolingpytest, CI pipelines, cloud tools
Machine learning and AItraining models and building AI featuresscikit-learn, PyTorch, model APIs

A command-line script takes its settings from the command line instead of input(): python report.py stock.csv --threshold 10. sys.argv holds the words typed, and the standard argparse module turns them into named options with help text. Automation scripts often walk folders with pathlib, read every CSV, and write a combined report, which is the data lab's pipeline pointed at real files.

Web back ends follow a pattern you already understand: a framework calls one of your functions for each request and sends back what it returns. In Flask, for example, a function decorated with a URL (@app.get("/api/stock")) returns a dictionary, which the framework sends to the browser as JSON. Everything inside that function is ordinary Python: load data, validate, summarise, handle errors.

# Not run here: a sketch of a tiny Flask web API (Flask is installed with pip)
from flask import Flask
app = Flask(__name__)

@app.get("/api/stock/low")
def low_stock():
    items, errors = load_items(read_stock_file())
    return {"low": summarize(items)["low_stock"], "problems": len(errors)}

What junior developers actually do: fix small bugs from a ticket queue, add a field to a report, write tests for existing code, update a script when a data format changes, and read a lot of other people's code. The skills that matter most are reading code and tracebacks, asking good questions, testing your changes, writing clear commit messages and taking code review feedback well. Communication counts as much as cleverness.

Worked example: a typical first ticket

  1. The ticket: "The weekly sales report crashes since the export added a Discount column with blanks."
  2. Reproduce it with the new export file and read the traceback: a ValueError converting "" to float on line 48.
  3. Write a test with a blank discount that fails, then fix the code to treat a blank as no discount, and the test passes.
  4. Rerun all the tests, open a pull request explaining the cause and the fix, and respond to the reviewer's comments.

Every step of that ticket uses something from this course: tracebacks, exceptions, testing and clear communication.

Automation
Using a program to do a repetitive task, such as producing a weekly report.
Command-line argument
A value typed after the script name, read with sys.argv or argparse.
Web framework
A library such as Django, Flask or FastAPI that calls your functions to handle web requests.
API
Application programming interface: a defined way for programs to talk to each other, often JSON over the web.
Pull request
A proposed code change shared for review before it is merged into the main code.

Remember: Scripts, data and web back ends all use the same core: read data, validate it, transform it, handle errors, test it.

Lesson 4: Tools, venv, pip and your next step

Goal: Explain virtual environments, pip and requirements files, name the everyday tools of a Python team, and plan your next credential and portfolio.

On your own computer you install Python from python.org (or your system's package manager), write code in an editor such as VS Code or PyCharm, and run it from a terminal with python script.py. Third-party packages come from the Python Package Index (PyPI) and are installed with pip, Python's package installer. This page cannot run pip or a terminal, so this lesson explains the commands rather than running them.

Different projects need different packages and versions: one needs an old version of a library, another the newest. A virtual environment (venv) is a private folder of packages for one project, so projects never interfere with each other or with the system's own Python. Create one per project, activate it, then install what the project needs.

# In a terminal, inside your project folder (not run in this page):
python -m venv .venv              # create a virtual environment in .venv
source .venv/bin/activate         # activate it (macOS and Linux)
.venv\Scripts\activate            # activate it (Windows)
python -m pip install requests pytest     # install packages into it
python -m pip freeze > requirements.txt   # record exact versions
python -m pip install -r requirements.txt # a teammate recreates them
python -m pytest                  # run the tests
deactivate                        # leave the environment

A requirements.txt file (or a pyproject.toml in newer projects) lists the packages a project needs, so anyone can recreate the environment with one command. The .venv folder itself is never shared or committed; the requirements file is. Running pip as python -m pip makes sure it installs into the Python you are actually using.

Everyday tools on a Python team
ToolWhat it is for
git and GitHub (or GitLab)version control: save history, branch, review changes in pull requests
pytestrunning tests; the most popular testing tool
A linter and formatter (such as Ruff, Flake8 or Black)catching common mistakes and keeping a consistent PEP 8 style automatically
A debugger (in VS Code or PyCharm)breakpoints and stepping through code, like this course's tracer
docs.python.orgthe official documentation: the library reference answers most questions

Your next step. The certificate from this course shows that you completed it; it is not an official industry certification. If you want a recognised credential, a natural next target is the Python Institute's PCEP (Certified Entry-Level Python Programmer) exam, followed by PCAP (Certified Associate in Python Programming). This course covers many of the topics they list, such as data types, control flow, collections, functions, exceptions, modules and classes; check the official syllabus and current fees on the Python Institute's site before booking. Employers weigh what you can show at least as much as certificates, so also build a portfolio: put your final project on GitHub with a README, tests and sample output, then add one or two projects of your own, such as automating a chore you know well.

Worked example: a 12-week plan after this course

  1. Weeks 1 to 2: install Python and VS Code, recreate your final project locally in a venv, put it on GitHub with a README and tests run by pytest.
  2. Weeks 3 to 6: build one more project from a real problem you know, ideally reading and writing real files; learn git branches and pull requests along the way.
  3. Weeks 7 to 9: pick a direction (web with Flask or Django, data with pandas and SQL, or automation) and follow its official tutorial; Data Lab on this site teaches SQL.
  4. Weeks 10 to 12: prepare for PCEP using the official syllabus, practise explaining your projects aloud, and start applying for junior developer, QA automation or data analyst roles.

Consistent, small steps beat bursts: an hour a day for twelve weeks is more than most bootcamps' contact time with the material.

pip
Python's package installer, which downloads packages from PyPI.
PyPI
The Python Package Index: the public repository of third-party Python packages.
Virtual environment (venv)
A private, per-project folder of installed packages, created with python -m venv.
requirements.txt
A file listing a project's packages and versions so the environment can be recreated.
Version control (git)
A system that records the history of code changes and lets teams work on them together.
PCEP / PCAP
Entry-level and associate Python certification exams from the Python Institute.

Remember: One venv per project, packages installed with python -m pip, versions recorded in requirements.txt. Next: a GitHub portfolio and the PCEP exam.

Practise it in Python Programming

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 7-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Mini project: stock report.

Every lesson is free: no ads, no lives and no paywall.