Creating and Importing Modules in Python

python_tutorials

Introduction

In Python, a module is a self-contained file with Python statements and definitions. For example, file.py, can be considered a module named file. This differs from a package in that a package is a collection of modules in directories that give structure and hierarchy to the modules.

Modules help us break down large programs into small files that are more manageable. With modules, code reusability becomes a reality. Suppose we have a function that is frequently used in different programs. We can define this function in a module then import it into the various programs without having to copy its code each time.

In this article, we will see how to create Python modules and how to use them in Python code.

Writing Modules

A module is simply a Python file with the .py extension. The name of the file becomes the module name. Inside the file, we can have definitions and implementations of classes, variables, or functions. These can then be used in other Python programs.

Let us begin by creating a function that simply prints “Hello World”. To do this, create a new Python file and save it as hello.py. Add the following code

To finish reading, please visit source site