Python Modules

WHAT IS A MODULE IN PYTHON?

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.

1. CREATE A MODULE IN PYTHON

To create a module just save the code you want (like shown below) in a file with the file extension .py

Let’s say “mymodule.py”

def greeting(name):
	print("Hello, " + name)
CREATE MODULE IN PYTHON
PROGRAM FILE – CREATE MODULE IN PYTHON

2. USE A MODULE IN PYTHON

Before using module we need another file suppose demo.py in the same folder.

CREATE MODULE IN PYTHON IN SAME FOLDER
CREATE MODULE IN PYTHON IN SAME FOLDER

Now we can use the module we just created, by using the import statement. Import the file with name you saved as, as we did mymodule (your might be different).

Now, simply we are accessing greeting function of module “mymodule.py” by using dot (.) followed by function name

moduleName.function(parameter)

# demo.py file

import mymodule mymodule.greeting("Jonathan")

OUTPUT:

IMPORT MODULE IN PYTHON
OUTPUT – IMPORT MODULE IN PYTHON

3. VARIABLES IN MODULE IN PYTHON

The module can contain functions, as already described, but also variables of all types even arrays, dictionaries, objects etc.

1. Create module: Save this code in “mymodule.py”

person1 = {
	"name": "John",
	"age": 36,
	"country": "Norway"
	}
MYMODULE FILE IN PYTHON
PROGRAM FILE – MYMODULE FILE IN PYTHON

2. Create main python file with any name like (demo.py): Import mymodule in this file (demo.py)

import mymodule
a = mymodule.person1["age"]
print(a)

OUTPUT:

ACCESS VARIABLE IN MODULE IN PYTHON
OUTPUT – ACCESS VARIABLE IN MODULE IN PYTHON

4. NAMING A MODULE IN PYTHON

You can name the module file whatever you like, but it must have the file extension .py

5. RE-NAMING A MODULE IN PYTHON

You can create an alias when you import a module, by using the as keyword:

import mymodule as mx
a = mx.person1["age"]
print(a)

OUTPUT:

RENAMING MODULE IN PYTHON
OUTPUT – RENAMING MODULE IN PYTHON

Leave a Reply

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