Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python modules

What are Python modules?

Educative Answers Team

A Python module is a Python file containing a set of functions and variables to be used in an application. The variables can be of any type (arrays, dictionaries, objects, etc.)

Modules can be either:

1. Built in

2. User-defined.

svg viewer

1) User-defined Modules

Create a Module

To create a module, create a Python file with a .py extension.

Call a Module

Modules created with a .py extension can be used in another Python source file, using the import statement.

svg viewer

Here’s an example of a simple module,
def myFunction( parameter ):  #define a function in
   print "Course : ", parameter

To call this Python module, create another Python file file and use the import statement.

   myModule.myFunction(“Python Programming”)

When the Python interpreter encounters an import statement, it imports the module if it is present in the search path.

A search path is a list of directories that the interpreter searches for importing a module.

When the above code is executed, the following output is produced:
def myFunction( parameter ):  #define a function in
  print ("Course : ", parameter)

2) Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Call a built-in Module

To call a built-in Module and use the function of that module write:

import moduleName #call a module
moduleName.function()#use module function
svg viewer
import math
print("The value of cosine is", math.cos(3))
print("The value of sine is", math.sin(3))
print("The value of tangent is", math.tan(3))
print("The value of pi is", math.pi)

Benefits of modules in Python

There are a couple of key benefits of creating and using a module in Python:

Structured Code

  • Code is logically organized by being grouped into one Python file which makes development easier and less error-prone.
  • Code is easier to understand and use.


Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.


python modules
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring