How to Create Modules in Python 3

In this article we want to learn How to Create Modules in Python 3, first of all let’s talk that What are Python Modules?

 

 

 

What are Python Modules ?

Module in Python is file that contains definitions, functions, classes and statements that can be reused in multiple programs. Module provides a way to structure and organize your code,  and after that it will easy to maintain and reuse the code.

 

 

Structure of Python Modules

Each module in Python has unique name, and you can import that into another Python program using import statement. after that the imported module acts as namespace, and you can access its functions, classes and variables using dot notation (like module_name.function_name).

for example, you could have module named “math_functions.py” that contains different mathematical functions, and after that you import that module into another code to use its functions. this allows you to write reusable and modular code that can be easily shared and maintained.

 

 

Python Built-in Modules

In addition to user defined modules, Python also have different built in modules, and these built-in modules provide common functionality, for example the math module is for mathematical operations, os module is for interacting with the operating system, and json module is for working with JSON data.

 

 

 

How to Create Modules in Python 3?

So now let’s talk about creating modules in Python.

These are the steps to create module in Python 3:

  1. Choose a file name for your module and save it with .py extension. for example, you can name your module my_module.py.
  2. Define functions, classes and variables inside the file. for example:

 

 

For using this module in another code, you can use import statement followed by the name of the module:

 

 

Note: You can also import specific objects from the module using from statement:

This way, you can use the imported objects directly in your script without having to qualify them with the name of the module.

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×