Chapter 5. Py Boxes: Modules, Packages, and Programs

During your bottom-up climb, you’ve progressed from built-in data types to constructing ever-larger data and code structures. In this chapter, you’ll finally get down to brass tacks and learn how to write realistic, large programs in Python.

Standalone Programs

Thus far, you’ve been writing and running code fragments such as the following within Python’s interactive interpreter:

>>> print("This interactive snippet works.")
This interactive snippet works.

Now let’s make your first standalone program. On your computer, create a file called test1.py containing this single line of Python code:

print("This standalone program works!")

Notice that there’s no >>> prompt, just a single line of Python code. Ensure that there is no indentation in the line before print.

If you’re running Python in a text terminal or terminal window, type the name of your Python program followed by the program filename:

$ python test1.py
This standalone program works!
Note

You can save all of the interactive snippets that you’ve seen in this book so far to files and run them directly. If you’re cutting and pasting, ensure that you delete the initial >>> and (include the final space).

Command-Line Arguments

On your computer, create a file called test2.py that contains these two lines:

import sys
print('Program arguments:', sys.argv)

Now, use your version of Python to run this program. Here’s how it might look in a Linux or Mac OS X terminal window using ...

Get Introducing Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.