Chapter 02 of 24 | Python

Your first program

Start with a complete script that prints a greeting. Create hello.py and type this example:

def main():
    print("Hello, world!")


if __name__ == "__main__":
    main()

def defines a function. The indented line belongs to that function. The final guard checks whether Python is running this file as the main program; if another file imports it, the guarded call does not run. For a one-line experiment, writing just print("Hello, world!") is fine. The function-and-guard pattern becomes useful as a program grows.

Run it and inspect failures

Open a terminal in the folder containing the file and run python hello.py. A successful run displays the greeting and returns to the prompt. If the command is unavailable, the interpreter may not be installed or its executable may not be on the command path. If Python reports a syntax error, inspect the indicated line and the line just before it.

Python source is case-sensitive: Print and print are different names. Parentheses are required when calling a function, and matching quotation marks delimit the string. The editor may highlight errors, but the interpreter's error message is the definitive result for that run.

Values and print formatting

name = "Ada"
year = 1843
print("Name:", name)
print(f"{name} wrote about the Analytical Engine in {year}.")

print accepts multiple values and separates them with spaces by default. An f-string evaluates expressions inside braces and formats the result as text. Use f-strings when they make output easier to read; do not concatenate values blindly, because combining text and numbers directly with + can raise a TypeError.

Command-line arguments

import sys

def main():
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} NAME")
        return 2
    print(f"Hello, {sys.argv[1]}!")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())

sys.argv is a list of strings; its first item is the script name. Check its length before indexing so a missing argument does not cause an IndexError. A process exit code of zero conventionally means success, while nonzero indicates a problem.

Beginner-to-master progression

Exercises

  1. Print a two-line poem and include a calculated result in an f-string.
  2. Accept a name argument and report a friendly usage message when it is missing.
  3. Run the same script directly and by importing it from another file. Explain the main guard's behavior.

From script to command-line interface

A script becomes an interface when other people or programs rely on its arguments and output. For more than a couple of arguments, use argparse instead of manually interpreting sys.argv. It can generate help text, validate required options, and distinguish flags from positional values.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet someone.")
    parser.add_argument("name")
    parser.add_argument("--loud", action="store_true")
    args = parser.parse_args()
    greeting = f"Hello, {args.name}!"
    print(greeting.upper() if args.loud else greeting)

if __name__ == "__main__":
    main()

As a program evolves, separate parsing arguments from the work they request. A test can call a pure greeting function without simulating terminal input, while a small main function coordinates the interface. This is the same separation used in larger applications: user interface at the edge, domain logic in reusable functions.

Mastery checkpoint

  1. Document your script's argument grammar, standard output, error output, and exit statuses.
  2. Make the useful behavior callable from both a command-line entry point and a unit test.
  3. Run python -m your_package or an installed entry point and explain how packaging changes invocation.
0% read