In Python, a module is a file that contains Python code, including definitions, functions, and statements that can be used in other programs. Modules allow you to organize and reuse code across different projects.
To create a module and store your defined functions in it, you can follow these steps:
.py
extension. This will be your module file. For example, create a file called mymath.py
.mymath.py
, you can define the cube()
and power()
functions as follows:Program (mymath.py)
def cube(a):
return a**3
def power(a,n):
return a**n
Now, you have created the module with the defined functions, you can use them in other programs in various ways.
The following program demonstrates how to import the entire module so that every function in the module is available in the program file. Remember that, module file and program file using module should be in the same location.
Program (test1.py)
# importing an entire module
import mymath
n = mymath.cube(10)
print('Cube =', n)
n = mymath.power(5,4)
print('Power =', n)
Output
Cube = 1000 Power = 625
If you only need one or a few functions from a module, you can import them directly. This technique allows you to use the imported function(s) without needing to reference the module name.
Program (test2.py)
# importing a specific function
from mymath import cube
# module name is not required to call function
n = cube(10)
print('Cube =', n)
Output
Cube = 1000
It is common to give a module an alias to provide a shorter and more convenient name for referencing it in your program. This is particularly useful when the module name is lengthy or prone to naming conflicts.
Program (test3.py)
#importing module using alias
import mymath as m
n = m.cube(10)
print('Cube =' , n)
n = m.power(5,4)
print('Power =', n)
Output
Cube = 1000 Power = 625
In this example, the module mymath
is imported with the alias m
. This allows you to use m
as a shorthand for referencing functions from the mymath
module.