Introduction
Modules in the Python programming language are the group of some instructions or functions or statements having a .py extension. For example, the math module, which most of us must have used at least once. If you remember, while using the factorial or sqrt function, we imported the math module, and then we used the functions. Here math is a module where different types of mathematical functions are defined. So to use all those functions, we simply have to import the module, and that's all!
In this article, we shall understand the reason for using modules and how we can create our own modules. Moreover, we shall also learn how the "import" keyword works.
Also See, Floor Division in Python.
Also See, Python Round Function.
Python Modules
We have already defined what a module is in the Python programming language. In real-world software programming, there can be thousands of lines of code in a project. It can become very tedious to manage and debug. Now, consider a situation where a certain segment of code is being used again and again. It is a very bad practice to write the same code again and again. A good idea would be to put that segment of code in a module and use it whenever required without having to code it again and again.
Check this out, python ord
Creating Modules In Python
We all must have used the math module in Python at least once. Let's now create our own module.
def multiply(first, second):
result = first * second
return result
The above code defines a simple method multiply, which takes two numbers as parameters and returns the product of the two numbers. In order to make it a module, all we need to do is save it as "module_name.py". We can save it as mult.py, where mult is the name which is provided by the user and .py is the extension denoting that the file is a module.
Now that we have saved the module, it's time to use it. To use the module, we need to import it. Importing a module is a very simple process. We just need to write the import keyword followed by the module name.
Example:
import mult
product = mult.multiply(2,6)
print(product)
Explanation:
- We first import the mult module which we created earlier.
- We call the multiply function using the module name and store the result in the product variable.
- To call a function, we must call it using module_name.function().
- Finally, the result is displayed as 12 at the console.
Variables In Module
Modules not only contain functions but also variables of all types such as arrays, objects, dictionary, etc.
Example:
myCar = {
"brand": "TATA",
"model": "Safari-Gold",
"price": "40 lacs"
}
We save the above code as car.py
We can now import the car module and get the model name like this:
import car
modelName =car.myCar["model"]
print(modelName)