How to create Python Modules

If we want to build a module, we need to save the script we want in a “.py” file. In this case, the name of the Python file is changed to become the name of the module.

For Example,

In this example, we will first create a function called “welcome” and save it as a module with the name newmodule.py i.e. name of the file, and with the extension “.py”.

Open your Visual studio code and go to the Explorer tab or simply press CTRL/CMD + Shift + E. That will open the Explorer tab. From there, under Desktop, left-click and click on New File. Create a new file name

newmodule.py

The file will open as a tab to code in. Type the following code:

def welcome (name):
  print("Hello, " + name +" to 30 Days of Python")

Using Python Modules

When we want to use the module in our program, we will use the import keyword. When we want to get only a few or specific methods or functions from a module, we will use the from keyword.

NOTE: This is how we use a function that is from a module we have imported:

module_name.function_name

Now to use the module which we have just created, we will use the import statement:

For Example,

In this example, we will Import the new module we named newmodule, and then call the function we created in that module with a given argument:

To do this, you can create a new Python file, or use the same Hello.py file we have been using from the onset. Anyway, whatever file you create or open to import a module, once it is saved, it will import.

Type in this code in a fresh IDE:

import newmodule
newmodule.welcome ("Tobby")

Output:

Hello, Tobby to 30 Days of Python

Ha-ha! There’s an error in my message while creating the function in the module earlier. But you get the point, right?

Instead of writing the new code every time, I can simply import this module and call that function without having to define anything in my new code.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials