Python modules; Through this tutorial, i am going to show you what is modules in python and how to use it.
Modules in Python
- What are the modules in Python?
- python create custom modules
- How to import modules in Python?
- How to use import and use module in python
- Built-in Modules in Python
- Python rename module on import
What are the modules in Python?
The modules in Python are those in which the code to do work is written in advance. You can create modules in Python by using python functions, classes, or variables, etc.
A file containing Python code, for e.g.: evenOdd.py, is called a module and its module name would be evenOdd.
Creating modules in Python has only one meaning. It converts your large program into a small manageable and organized file. So that you can reuse it easily.
If you have to repeatedly check-in your Python program whether this number is even or odd. So you have to write the same code again and again. And if you make a module. So you just have to include it in the program and just call it. So this will tell you whether the given number is even number or odd number.
Python create custom modules
You know about the above python modules. Now let’s see how you create modules and write code in modules:
Look like you built the module in python. Which return that the given number is even or even number.
Now first create a module file named evenOdd.py. After this, the number in the file evenOdd.py is even or Od is made its function.
# Python Module example def evenOddFunc( x ): if (x % 2 == 0): return "This is even number" else: return "This is odd number"
How to import modules in Python?
Created a module in Python. Now will make the module import our function.
In Python, use the import keyword to import a custom created module and inbuilt model.
The following is how to import the module using the import keyword:
How to use import and use module in python
So far you have imported the module in Python. And will see how to use the module. Or how to call a function created inside a module.
For this, you have to type the name of the module and then write ” dot “. After this you have to write the name of the function which you have to call from the module.
Note: – A Python module can have more than one function.
Let’s see below:
import evenOdd x = evenOdd.evenOddFunc(10) print(x)
Built-in Modules in Python
Python consists of inbuilt modules. Which are already made? You can only call and use them according to your requirements.
Python has a lot of inbuilt modules. Such as math modules, calendar module, etc.
So let see the program to how to use inbuilt modules in python:
# to import math module import math print("The value of pi is", math.pi)
Python rename module on import
If you have imported the module and you want to change its name. So you can:
# to import math module import math as mx print("The value of pi is", mx.pi)
Its output will also be similar to the above-given program output.