Programming with Python › Python Setup and First Programs › Day 49

Day 49: Your First Real Program

Day 49 of 365 — Your First Real Program

After this lesson you will be able to assemble a complete, small Python program from named functions, a main entry point, and the main-guard idiom — one that reads input, validates it, does one useful job, handles bad input gracefully, and can be tested.

Course
Programming with Python
Category
Python Setup and First Programs
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-049-your-first-real-program

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/programming-with-python/day-049-your-first-real-program
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language


Historical background


What it is — and what it is not

A real program is:

It is not:


Why it was created and what problems it solves


How it works

The anatomy of a program

Diagram: how a program's exit status reaches the caller

Diagram: the anatomy of a small Python program — imports, functions, the main function, and the entry-point guard

'''One line saying what this does.'''
import sys


def parse_args(argv): ...
def process(rows): ...
def report(result): ...


def main(argv=None):
    args = parse_args(argv or sys.argv[1:])
    try:
        result = process(load(args.path))
    except FileNotFoundError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1
    report(result)
    return 0


if __name__ == "__main__":
    sys.exit(main())

The main-guard idiom, precisely

Diagram: a script with and without a main guard

Designing before coding: inputs, processing, outputs

Diagram: the four questions to answer before writing a program

Flowchart: a program's runtime flow from input through validation and processing to output, with a branch to error handling

Script, notebook, or package: three homes for code (A13)

Diagram: a notebook compared with an importable module

HomeWhen it is rightWhat it costs
A notebookExploring, once, with output beside the codeHidden state; painful to diff and test
A scriptOne task, run from a command lineNot importable as a library
A packageReused, imported, versioned, distributedStructure and packaging to maintain

Readability: names, small functions, and PEP 8

Diagram: separating pure computation from input and output


An everyday analogy

A well-organised recipe, versus notes on the back of an envelope.

CookingThe program
The ingredients listInputs, validated up front
Numbered method stepsNamed functions
”Serves four” at the topThe docstring
A sub-recipe referenced by nameA helper function
”If the sauce splits, do this”Error handling
Notes scribbled out of orderA notebook
The published, tested versionA module

Examples in practice

Diagram: unclear variable names compared with descriptive ones


Implications: security, privacy, performance, scalability, and cost

Diagram: validating input at a single boundary compared with checking everywhere


Alternatives: free, open source, and commercial

Diagram: a docstring restating the code compared with one explaining intent

ToolTypeWhere it fits
A plain scriptFree, built inOne task, run by hand or on a schedule
argparseFree, standard libraryReal options and help text — Day 80
pathlibFree, standard libraryPaths, cleanly
Black + RuffFree, open sourceFormatting and linting, per Day 37
pytestFree, open sourceTesting what you made importable — Day 71
Cookiecutter templatesFree, open sourceA package skeleton, when you get there

TermWhat it actually is
ModuleA .py file, importable by name
ScriptA module intended to be run
PackageA directory of modules, importable as a unit
__name__"__main__" when run, the module name when imported
Entry pointThe function the guard calls
Exit statusThe integer the process returns — Day 41 reads it
PEP 8The shared style convention

When to use it — and when not to

Diagram: the real cost of splitting a program into functions


The AI connection

Knowledge check

quiz:
  question: "A colleague imports one helper function from your script, and their program immediately runs your entire data pipeline. What is missing?"
  options:
    - "The top-level code should sit inside a function called from a main-guard block"
    - "The helper function should be marked private with a leading underscore"
    - "The script needs an __init__.py so Python treats it as an importable module"
    - "The import should have used importlib to avoid executing the module"
  answer_index: 0
  explanation: "Importing a module runs every statement at its top level - that is how Python defines the functions in it. Work placed at module level therefore runs on import too. The guard is what distinguishes run-me from import-me, and without it a file cannot safely be both."

Hands-on exercise

Turn a working script into a program with a shape. Worked through fully in the Day 49 lab directory.

What you are doingCommand or step
Write the three lines firstinputs, processing, outputs — before any code
Add the guardthe __name__ check calling sys.exit(main())
Prove it workspython3 prog.py runs; import prog does not
Return a statusreturn 1 on failure, 0 on success
Check it from the shellpython3 prog.py; echo $?
Extract a pure functionOne with no I/O, and call it from a test
Format and lintblack . and ruff check .

Expected output

$ python3 prog.py data.csv
processed 142 rows, total 8134.50
$ echo $?
0
$ python3 prog.py missing.csv
error: [Errno 2] No such file or directory: 'missing.csv'
$ echo $?
1
$ python3 -c "import prog; print(prog.summarise([]))"
0

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. Which of the following best describes what makes a program "real" in this lesson's sense?

  1. It does one job, handles errors, and is readable and testable
  2. It is at least a few hundred lines long
  3. It uses advanced language features and clever one-liners
  4. It runs correctly the first time you type sensible input
Show answer

Answer: A. It does one job, handles errors, and is readable and testable

A real program is defined by properties, not size: it does one useful thing, takes input and handles bad input gracefully, produces clear output, and is readable and testable. Forty well-structured lines qualify; thousands of tangled ones may not.

Q2. What does the line `if __name__ == "__main__":` actually do?

  1. It defines the main function that Python runs first
  2. It runs the block only when the file is executed directly
  3. It imports the standard library so the program can start
  4. It marks the file as the most important module in the project
Show answer

Answer: B. It runs the block only when the file is executed directly

Python sets a file's `__name__` to `"__main__"` only when that file is run directly. When the file is imported, `__name__` is the module name instead. The guard therefore runs the program's startup code only on direct execution — which is what lets a test import the file's functions without launching the whole program.

Q3. Why is the main-guard idiom what makes your program testable?

  1. It automatically generates test cases for every function
  2. It speeds the program up so tests finish faster
  3. Another file can import your functions without running them
  4. It prevents the program from ever crashing
Show answer

Answer: C. Another file can import your functions without running them

Because the guard holds back execution on import, a test file can do `from converter import celsius_to_fahrenheit` and check that function in isolation. Without the guard, importing the file would run all of its top-level code — printing, prompting, and exiting.

Q4. You design a program before coding by writing three lists. What are they?

  1. Variables, loops, and functions
  2. Imports, comments, and tests
  3. Bugs, fixes, and releases
  4. Inputs, processing, and outputs
Show answer

Answer: D. Inputs, processing, and outputs

The lightweight design step is to list the inputs (what the program needs and from where), the processing (what it does with them, including validation), and the outputs (what it produces and where, including failure behavior) — then write the code.

Q5. A user runs `python3 converter.py hot C`. In the well-structured version, what happens?

  1. `parse_args` raises ValueError; `main` prints an error, exit 1
  2. The program crashes with a raw traceback and exit code 0
  3. The program silently converts 0 degrees and prints a result
  4. The program asks the user to type the value again
Show answer

Answer: A. `parse_args` raises ValueError; `main` prints an error, exit 1

Input is validated at the boundary. `float("hot")` fails, so `parse_args` raises a `ValueError` with a readable message; `main` catches it, prints the message and a usage line to `sys.stderr`, and returns a non-zero exit code so callers know it failed.

Q6. Why should error messages be printed to standard error (`sys.stderr`) rather than standard output?

  1. Standard error is faster than standard output
  2. It keeps results separate from diagnostics
  3. Standard output cannot display error text
  4. It hides the error from the user entirely
Show answer

Answer: B. It keeps results separate from diagnostics

Sending diagnostics to `stderr` and results to `stdout` means a program that pipes the converter's output elsewhere receives only the clean result on success, while error messages travel on a separate stream — a standard convention for command-line tools.

Q7. Which statement about `eval()` and user input is correct?

  1. `eval()` is the recommended way to turn user text into a number
  2. `eval()` is safer than `float()` because it validates types
  3. `eval()` runs whatever string it is given as Python code
  4. `eval()` only works on numbers, so it is harmless
Show answer

Answer: C. `eval()` runs whatever string it is given as Python code

`eval()` runs its argument as Python code, which means a malicious string could do real damage. To turn text into a number safely, use `float()` (or `int()`), which can only produce a number or raise an error — never run code.

Q8. When is it reasonable NOT to add a main guard, validation, and functions?

  1. When the program will be given to other people to run
  2. When the program must run unattended on a schedule
  3. Whenever you are in a hurry
  4. During throwaway exploration, used once by you
Show answer

Answer: D. During throwaway exploration, used once by you

Genuine throwaway exploration — poking at data in a notebook or the interactive prompt, for your eyes only, with no future — does not need the full structure. But the moment code becomes a tool someone relies on, or must run more than once, it deserves the structure.

Glossary

program
A complete piece of software that does one useful job end to end: it reads input, processes it, produces clear output, handles bad input gracefully, and is organized so it can be read and tested.
function
A named, reusable unit of code that does one job, defined in Python with `def`; it has its own local variables and can return a value, which makes it testable in isolation.
main guard
The line `if __name__ == "__main__":` at the bottom of a file, which runs the program's startup code only when the file is executed directly, not when it is imported.
__name__
A built-in variable Python sets for every module: it equals the string `"__main__"` when the file is run directly, and the module's own name when the file is imported by another.
docstring
A string literal placed as the first line inside a function, class, or module that documents what it does; tools and the built-in help system read it.
edge case
An input at the boundary of what a program expects — empty input, the wrong type, or an out-of-range or impossible value — that must be handled deliberately rather than assumed away.
input validation
Checking input at the boundary of a program to confirm it meets expectations, and refusing bad input with a clear message instead of crashing or computing a wrong answer.
module
A single Python `.py` file, which can be run as a program or imported by other files to reuse its functions and variables.
script
A Python file meant to be run start-to-finish from the command line to do one job, as opposed to a notebook (interactive cells) or a package (a directory of modules).
return value
The value a function hands back to its caller with the `return` statement; testing a function means calling it and checking that its return value is what you expected.
PEP 8
The official style guide for Python code, which codifies conventions such as `lower_case_with_underscores` names, four-space indentation, and short lines to keep code readable and consistent.
exit code
A small integer a program returns to the operating system when it ends: 0 conventionally means success, and any non-zero value means an error occurred, so other programs can detect failure.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.