Skip to content

Module 20 · Building Real Python Applications — topic 3 of 13

Program structure

Laying out a complete application: module docstring, imports, constants, functions and classes, a main() entry point with a command loop, exit codes, and how the structure grows into a package.

Beginner 10 min read·Lesson 296 of 306 in Python Programming

Learning objectives

  • Lay out a script in a conventional order
  • Write a main() entry point and command loop
  • Return exit codes and plan the move to a package

Definition

Program structure is the overall layout of an application's code: where configuration, definitions and the entry point live, and how control flows from start-up through a main loop to exit.

Introduction

Opening a well-structured Python file, you know where to look: settings at the top, functions in the middle, the entry point at the bottom.

Why it matters

A predictable structure makes programs easier to navigate, test and grow from a single file into a package.

Detailed explanation

A conventional file order: module docstring, imports (standard library, third-party, local), constants and configuration, classes and functions, then the entry point.

main() contains the top-level flow — parse arguments, run the command loop, return an exit code — and is called under if __name__ == "__main__":.

raise SystemExit(main()) passes main's return value to the operating system as the exit code (0 for success).

A command loop reads a command, dispatches it to a handler, prints the result and repeats until the user quits.

Handlers should be small functions that call into the logic layer rather than containing the logic themselves.

Keep state (the list of expenses, settings) in variables or objects created in main() and passed to handlers, not in scattered globals.

When the file grows beyond a few hundred lines, move groups of code into modules of a package (models.py, storage.py, cli.py) and keep a thin __main__.py.

Structure the program so the logic can be tested without running the interactive loop.

Syntax

Python
"""Expense tracker (command line)."""
import sys
APP_NAME = "Expense Tracker"
def add_expense(expenses, amount, category): ...
def main(argv):
...
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
  • Docstring, imports, constants, definitions, entry point.
  • main() returns an exit code.
  • Thin handlers, testable logic.

Code examples

A conventional layout

Python
"""Expense tracker (command line)."""
import sys
APP_NAME = "Expense Tracker"
VERSION = "1.0"
def banner():
return f"{APP_NAME} v{VERSION}"
def main(argv):
print(banner())
print("commands:", ", ".join(["add", "list", "report"]))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
Output
Expense Tracker v1.0
commands: add, list, report

Growing into a package

Text
expense_tracker/
├── tracker/
│ ├── __init__.py
│ ├── __main__.py # calls cli.main()
│ ├── cli.py # command loop and handlers
│ ├── models.py # Expense dataclass
│ ├── service.py # business rules
│ └── storage.py # JSON persistence
├── tests/
├── requirements.txt
└── README.md

More examples

A command loop

Python
def run(commands):
expenses = []
for line in commands:
cmd, _, rest = line.partition(" ")
if cmd == "add":
amount, category = rest.split(maxsplit=1)
expenses.append((float(amount), category))
print(f"added {category} {float(amount):.2f}")
elif cmd == "list":
for i, (a, c) in enumerate(expenses, 1):
print(f"{i}. {c:<8}{a:>8.2f}")
elif cmd == "quit":
print("bye")
break
else:
print(f"unknown command: {cmd}")
run(["add 250 food", "add 40 travel", "list", "remove 1", "quit", "add 1 never"])
Output
added food 250.00
added travel 40.00
1. food      250.00
2. travel     40.00
unknown command: remove
bye

Step-by-step explanation

  • The loop reads one command at a time; in the real app the list would be replaced by input() calls.
  • partition splits off the command name and leaves the rest as arguments.
  • quit ends the loop, so the final command is never processed.

Expected output

Running “A command loop” prints exactly:

TextOutput
added food 250.00
added travel 40.00
1. food 250.00
2. travel 40.00
unknown command: remove
bye

Practical applications

  • Interactive shells such as the Python REPL and database clients.
  • Chatbots and menu-driven tools.

Best practices

  • Follow the conventional file order.
  • Keep the command loop thin.
  • Pass input in so the loop can be tested.

Common mistakes

Code at module level

Avoid

expenses = []
while True:
cmd = input() # runs on import!

Prefer

def main():
expenses = []
while True:
...
if __name__ == "__main__":
main()

Importing the module for tests would start the interactive loop.

Important notes

  • argparse adds proper command-line options for non-interactive use: tracker add 250 food.

Key takeaways

  • Docstring, imports, constants, definitions, main().
  • main() runs the loop and returns an exit code.
  • Grow into a package when the file gets large.

Try it yourself

  1. 1
    Add report and help commands to the command loop.
  2. 2
    Restructure one of your earlier scripts into the conventional layout.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “Building Real Python Applications” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat does MVP stand for when planning an application?
  • AdvancedWhere should input validation ideally happen?
  • AdvancedWhat is printed?
Practise this module