Module in Python programming language

A module is a Python file where you can include different variables, functions, and classes that perform some programming tasks.

How to create a module in Python programming language?

Create a new file like this “modulename.py” and then write python codes(variables, functions, and classes).

Example

We have created a module “names.py” that will contain a function that will take a name and then will print a welcome message.

We define this function in our module and we call it in another Python file.

#____ProgrammerCodes.com____

def welcome(name):
    print("Welcome", name)

#____ProgrammerCodes.com____

To call the function that is in the module, We first need to import the module into Python file and then call the function.

#____ProgrammerCodes.com____

import names

names.welcome("Sarah")

#____ProgrammerCodes.com____

We write the module name before the dot “.” and after that, we write the function name.

Result:

Welcome Sarah

To call a variable from that module, we define a variable in the module then we call it from the Python file.

The module contains a variable:

#____ProgrammerCodes.com____

name = "Sarah"

#____ProgrammerCodes.com____

In the Python file, we write:

#____ProgrammerCodes.com____

print(names.name)

#____ProgrammerCodes.com____

Result:

Sarah

To import all variables, classes, and functions of a module, you have to write ” from modulename import * “.

To import a specific variable, function, and class, you have to write ” from modulename import functionname1, functionname2 “.

When you import a module using “from X import Y “, you don’t have to use the dot that we used in the last examples so instead of “names.welcome()” you just write welcome().

Summary

Python modules help you to organize your code and use it in multiple projects and files. There are a lot of Python built-in modules and external modules that you can use the same way that we explained in this article.

Tutorial’s Question

How to import a specific function that exist in a module?

  • from * import functionname
  • from modulename import functionname
  • from modulename import functionname()

Simple Examples

If you have learned the basics of Python and you want to see some simple examples about these concepts such as numbers, for loop, function, and so on, I suggest you visit these articles below:

Leave a Comment

Your email address will not be published. Required fields are marked *