Python Modules is a separate program that has its own functions and code. We can say the module is the same as a code library that contains a set of functions, if you want, you can use it in your application.
Here is Import a Module lesson, and more.
The Advantage of use Python Modules is
- It’s broken down large programs into small manageable and organized files.
- Modules provide the reusability of code.
- Using an inbuilt or third-party module(library) can reduce time and effort.
Create a Python Modules
You just need to save the code in python file (extension
.py), it will be a module.
Module file named
mymodule.py, This is a custom module example.
def message(msg): print("Module print, " + msg)
How to import modules in Python?
By using the
import statement, you can use the module
mymodule.py , like this example.
In Hello.py import the module and passing the value to “message” function of “mymodule“.
import mymodule mymodule.message("Hello")
Output: Module print, Hello
Variables in Module
Module file mymoduel.py with a list variable
varList = ['a', 1, 'b', 2]
importing file in Hello.py print(), accessing list variable and in the console.
import mymodule print(mymodule.varList)
Output : [‘a’, 1, ‘b’, 2]
Import Standard Modules of Python
Import is searched for the module initially in the local scope by
calling __import__() function.
math module is a standard module of python.
import math print(math.factorial(5))
For a complete tutorial with example follow the “How Python Import-Module“.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python Modules Example are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.