Python Module – Python Programming

Python Module can be thought of as a package in Java. A module permits you to logically organize your Python code. Consider a module to be constant as a code library. We can store Functions, Variables, Classes in Module.

Python Modules - Built-In Modules,  Create a Module, Python Import Statement, Renaming Module name, Accessing Specific Part from Module
Image by Harry Strauss from Pixabay

Built-In Modules

Python has a built-in module which we can use according to our needs. For example – 

import platform
a = platform.system()
print(a)

Create a Module

To create a module just save the code you want in a file with the file extension mymodule.py:

def greeting():
   print("Hello from module")
   person = {"name":"Huzaif","age":22,"country":"India"}

Above we have created a function and dictionary variable. Save the file in the same folder.

Python Import Statement

The import statement help to import or use the module which we have created. Use the module file name. Example: mymodule

import mymodule
mymodule.greeting("name")     # Accessing Function from mymodule.py
print(mymodule.person["age"]) # Accessing Variable from mymodule.py

Renaming Module name

You can rename module name by using as keyword

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

Accessing Specific Part from Module

For Accessing Specific Part from Module we use from keyword

from mymodule import person
print(person["age"]) # we have accessed only person variable

Whats Next – Python – Try…Except…Finally

Share