13Modules

So far in this book you have been writing all your code in a single Python file (with the .py extension). With Python, you can put your code, specifically functions and variables, in any number of .py files, creating what are called modules.

What Is a Module?

A module is a file containing a set of functions that you want to include in your program. Rather than re-create the same function or variable across various Python programs, you could store the function or variable inside a module and import that module into multiple Python programs. Modules also help provide organization for Python programs. Instead of having all the code in one file, you can group pieces of the code together in separate modules—like how a book organizes information into chapters. Modules make functions even more reusable by enabling you to import a module from a file outside the file in which you are writing a Python program. Although modules can be imported into a program, a module itself is not a program.

Create a Module

You create a module by saving the code you write in a file with a .py extension. As a reminder, the .py extension is the extension for Python files. The file itself can contain functions as well as variables.

Let's create your first module that will be reused throughout this chapter! The module consists of functions and variables that are used to provide information about the planets in the solar system.

In IDLE, create a new file and save the file as solarsystem.py ...

Get Bite-Size 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.