Programming with Python › Python Setup and First Programs › Day 49
Day 49: 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.
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
- 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 - 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 - 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.
- 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:
- List the five properties that make a program "real" — does one useful thing, handles input and errors, gives clear output, is readable, and is testable — and check them against a program
- Explain what `if __name__ == "__main__":` does and why it lets a file be both a runnable program and an importable, testable module
- Design a small program before coding it by listing its inputs, processing steps, outputs, and edge cases
- Structure a program as small named functions with docstrings plus a `main()` that orchestrates them and returns an exit code
- Validate input at the boundary and report bad input with a clear message and a non-zero exit code, never with a raw traceback or a silent wrong answer
- Test a program the built-in way by importing a function and asserting its return value, and run a file as a module with `python -m`
- Apply basic PEP 8 readability — meaningful names and small functions — and explain why user input must never be passed to `eval()`
Prerequisites
- Days 43-48 of this course: a working Python 3 install, plus variables and types, strings, numbers, input/output with f-strings, and reading error messages
- Comfort running a script from the terminal with `python3 file.py` and editing a text file
Why this matters
-
This is where the week’s pieces become a program rather than a collection of snippets.
-
The shape you learn today is the shape of every script you will write — for data, for training, for deployment.
-
The main guard is not decoration. It is what makes a file both runnable and importable.
-
Readable code is a professional requirement, because you will read it far more often than you wrote it.
-
A program that exits with a meaningful status is a program automation can use, per Day 41.
The idea in plain language
-
A program is not a pile of statements. It has a shape: inputs, processing, outputs, and a way to fail.
-
Design before coding — decide what goes in, what comes out, and what could go wrong.
-
Small named functions are how a program stays readable and testable.
-
The main guard separates “run me” from “import me”.
-
Conventions are not taste. PEP 8 exists so that every Python file looks familiar to every Python reader.
Historical background
-
Structured programming was an argument, not an obvious truth. Through the 1960s, control flow jumped anywhere, and reading a program meant tracing it.
-
The case for functions and blocks was that a reader could understand one piece without holding the whole in mind.
-
PEP 8, published in 2001, applied the same reasoning to layout: consistency so that reading is automatic.
-
The main guard is Python-specific and follows from modules being ordinary code — importing a file runs it, so anything that should not run on import goes inside the guard.
-
Notebooks arrived later and reintroduced an old problem: cells run out of order, so the file no longer describes what happened.
-
The resolution is not to abandon notebooks but to know which of the two you are in, and why.
What it is — and what it is not
A real program is:
- Structured: inputs validated, work in named pieces, results reported.
- Importable, so its parts can be tested and reused.
- Explicit about failure, with a status a caller can read.
It is not:
-
Not longer. Structure usually makes a program shorter, because repetition becomes a function.
-
Not a notebook. A notebook has hidden state and no ordering guarantee.
-
Not finished when it works once. It is finished when it fails clearly.
-
Not a matter of taste. The conventions exist so a stranger can read it, and the stranger is usually you.
Why it was created and what problems it solves
-
Comprehension. A named function is a unit a reader can understand without the rest.
-
Testability. Logic separated from side effects can be tested without a network, a file, or a GPU.
-
Reuse. A file that is importable is a file another program can call.
-
Predictability. Top-to-bottom execution means the file describes what happened, which a notebook does not.
-
Composability. Arguments in, status out — the interface Day 41’s automation expects.
How it works
The anatomy of a program
'''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())
- Imports at the top, standard library first.
- Small named functions, each doing one thing.
mainorchestrates and returns a status rather than callingexititself.- The guard runs it only when the file is executed directly.
The main-guard idiom, precisely
-
__name__is"__main__"when the file is run directly, and the module’s name when it is imported. -
So the guard means “only when run, not when imported”.
-
Without it, importing the file runs everything — which breaks tests, breaks reuse, and surprises anyone who imports one function from it.
-
sys.exit(main())turns the return value into the process’s exit status, which Day 41’s pipeline reads.
Designing before coding: inputs, processing, outputs
-
Write the inputs, outputs and failures down first, in three lines, before any code.
-
Inputs: where does the data come from, and what must be true of it?
-
Processing: what is the transformation, in one sentence?
-
Outputs: what does success look like, and where does it go?
-
Failures: what can go wrong, and what should happen when it does?
-
Ten minutes here saves an hour of restructuring, and it is the step people skip.
Script, notebook, or package: three homes for code (A13)
| Home | When it is right | What it costs |
|---|---|---|
| A notebook | Exploring, once, with output beside the code | Hidden state; painful to diff and test |
| A script | One task, run from a command line | Not importable as a library |
| A package | Reused, imported, versioned, distributed | Structure and packaging to maintain |
-
The signal to leave a notebook is reuse. The moment you copy a cell, that code belongs in a file both places import.
-
The signal to become a package is a second consumer, not size.
Readability: names, small functions, and PEP 8
-
Names carry the meaning.
rows,total_amount,is_valid— notx,d,tmp. -
A function should fit on a screen and do one thing you can name.
-
PEP 8 is the shared convention: four spaces,
snake_case, imports at the top, two blank lines between top-level definitions. -
Let a formatter do it, per Day 37. The rules stop being something you think about.
-
A docstring says what and why, not how — the code already shows how.
An everyday analogy
A well-organised recipe, versus notes on the back of an envelope.
| Cooking | The program |
|---|---|
| The ingredients list | Inputs, validated up front |
| Numbered method steps | Named functions |
| ”Serves four” at the top | The docstring |
| A sub-recipe referenced by name | A helper function |
| ”If the sauce splits, do this” | Error handling |
| Notes scribbled out of order | A notebook |
| The published, tested version | A module |
-
Notes work for the person who wrote them, that evening. They stop working a month later and they never worked for anyone else.
-
The numbered method is not more work. It is the same content, arranged so it can be followed.
Examples in practice
-
A script that runs its whole workload on import, discovered when someone tries to import one function from it for a test.
-
A 300-line
main()that cannot be tested because every line touches the network. -
A notebook that works top to bottom for its author and not for anyone else, because cell 12 was run before cell 7.
-
A script that always exits zero, so the pipeline calling it never notices a failure.
-
Variables named
df,df2anddf_final, which was clear for an hour.
Implications: security, privacy, performance, scalability, and cost
-
Security: validate inputs at the boundary, once, rather than defensively everywhere. A single validated entry point is auditable.
-
Never interpolate an argument into a shell command — Day 45’s rule, and scripts are where it usually happens.
-
Privacy: what a program prints, it may log. Decide deliberately what goes to
stdoutin something that runs unattended. -
Performance: structure costs nothing measurable. A function call is nanoseconds, and the readability is worth far more than it.
-
Scalability of understanding is the real constraint. A program nobody can read cannot be safely changed, whatever its runtime.
-
Cost: the expensive code is the code that must be rewritten because nobody can work out what it does.
Alternatives: free, open source, and commercial
| Tool | Type | Where it fits |
|---|---|---|
| A plain script | Free, built in | One task, run by hand or on a schedule |
argparse | Free, standard library | Real options and help text — Day 80 |
pathlib | Free, standard library | Paths, cleanly |
| Black + Ruff | Free, open source | Formatting and linting, per Day 37 |
pytest | Free, open source | Testing what you made importable — Day 71 |
| Cookiecutter templates | Free, open source | A package skeleton, when you get there |
-
Adopt the formatter and linter on day one of a project. They cost one line of configuration and remove a whole category of decision.
-
Do not start with a package. Start with a script, and promote it when a second thing needs to import it.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Module | A .py file, importable by name |
| Script | A module intended to be run |
| Package | A directory of modules, importable as a unit |
__name__ | "__main__" when run, the module name when imported |
| Entry point | The function the guard calls |
| Exit status | The integer the process returns — Day 41 reads it |
| PEP 8 | The shared style convention |
When to use it — and when not to
-
Use the guard in every file that can be run. It costs two lines.
-
Return a status from
mainrather than callingsys.exitdeep inside the logic. -
Keep functions small and named for what they do.
-
Separate pure logic from input and output, so the logic can be tested alone.
-
Do not put the workload at module level. Importing should have no side effects.
-
Do not build a package for one script.
-
Do not keep reusable code in a notebook. Move it to a file the notebook imports.
The AI connection
-
Every training script has this shape: parse arguments, load data, run, report, exit with a status.
-
The main guard is what makes a module importable, which is how a training script becomes something a test or a sweep can call.
-
Notebook to script is the transition that matters most in AI work. A notebook explores; anything reused belongs in a file that both places import.
-
Separating pure logic from side effects is what lets you test a metric calculation without a GPU, a network, or a dataset.
-
Exit codes are how a pipeline knows. Day 41’s automation reads that number, and a script that always exits zero is invisible to it.
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 doing | Command or step |
|---|---|
| Write the three lines first | inputs, processing, outputs — before any code |
| Add the guard | the __name__ check calling sys.exit(main()) |
| Prove it works | python3 prog.py runs; import prog does not |
| Return a status | return 1 on failure, 0 on success |
| Check it from the shell | python3 prog.py; echo $? |
| Extract a pure function | One with no I/O, and call it from a test |
| Format and lint | black . 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
-
The exit status differs between success and failure, which is what Day 41’s automation reads.
-
Importing printed nothing, which is the guard doing its job.
Validate your work
- Your file runs when executed and stays silent when imported
-
mainreturns a status, and the shell sees it in$? - At least one function is pure and testable without I/O
- Errors are reported on
stderr, per Day 47 -
blackandruffboth pass -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
Importing runs everything. Work is at module level. Move it inside
main. -
$?is always 0.mainreturnsNone, which becomes 0. Return an integer. -
sys.exit("message")sets status 1 and prints the message tostderr— useful, and different from returning an integer. -
The linter objects to your import order. Let the formatter fix it rather than arguing.
Common mistakes
-
No main guard.
-
A
main()that does everything, so nothing can be tested. -
Calling
sys.exitdeep inside a helper, which makes it unusable as a library function. -
Names that were clear for an hour.
Practice assignment
-
Take a script you already have and restructure it: guard,
main, small functions, a status. -
Write the three design lines first for your next script, and note afterwards whether the structure matched them.
-
Extract every pure function from a program that mixes logic and I/O, and write one test for each.
-
Import your own script from another file and confirm nothing happens.
Extension challenge
-
Convert a notebook into a module plus a thin notebook that imports it, and note how much of the notebook was reusable logic.
-
Add
argparsewith--help, one option and one positional argument, and compare it with thesys.argvversion from Day 47. -
Make your program a package: a directory, an
__init__.py, and a console entry point. Day 83 does this properly. -
Write a test that imports
mainand calls it with a crafted argument list, asserting on the returned status rather than on printed output.
Quiz
Q1. Which of the following best describes what makes a program "real" in this lesson's sense?
- It does one job, handles errors, and is readable and testable
- It is at least a few hundred lines long
- It uses advanced language features and clever one-liners
- 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?
- It defines the main function that Python runs first
- It runs the block only when the file is executed directly
- It imports the standard library so the program can start
- 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?
- It automatically generates test cases for every function
- It speeds the program up so tests finish faster
- Another file can import your functions without running them
- 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?
- Variables, loops, and functions
- Imports, comments, and tests
- Bugs, fixes, and releases
- 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?
- `parse_args` raises ValueError; `main` prints an error, exit 1
- The program crashes with a raw traceback and exit code 0
- The program silently converts 0 degrees and prints a result
- 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?
- Standard error is faster than standard output
- It keeps results separate from diagnostics
- Standard output cannot display error text
- 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?
- `eval()` is the recommended way to turn user text into a number
- `eval()` is safer than `float()` because it validates types
- `eval()` runs whatever string it is given as Python code
- `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?
- When the program will be given to other people to run
- When the program must run unattended on a schedule
- Whenever you are in a hurry
- 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
- The Python Tutorial — Python Software Foundation (accessed 2026-07-12)
- Defining Functions — Python Software Foundation (accessed 2026-07-12)
- What Does if __name__ == "__main__" Do? — Real Python (accessed 2026-07-12)
- PEP 8 — Style Guide for Python Code — Python Software Foundation (accessed 2026-07-12)
- Automate the Boring Stuff with Python — Al Sweigart (accessed 2026-07-12)
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.