0% completed
A module in Python is a file that contains Python functions, classes, and variables that can be reused across different programs. Instead of writing the same code repeatedly, you can define it once in a module and import it wherever needed.
Using modules makes Python programs organized, reusable, and easier to manage. Python provides:
math
, random
, os
)Modules help in code reusability, better structure, and easier debugging by breaking large programs into smaller, manageable parts.
A module is simply a Python file (.py
) that contains functions and variables. To use a module, we import it using the import
statement.
Create a file called my_module.py
with the following content:
Now, you can import and use this module in another script.
To use the module, import it in another Python script.
import my_module
loads all functions and variables from my_module.py
.my_module.greet("Alice")
calls the greet()
function from the module.my_module.PI
accesses the PI
variable from the module.Instead of importing the entire module, you can import only specific functions or variables.
from my_module import greet
imports only the greet
function.my_module.greet()
, you can call greet()
directly.You can use aliases (as
) to rename modules or functions when importing.
import my_module as mm
allows using mm.greet()
instead of my_module.greet()
.from my_module import greet as hello
renames greet()
to hello()
.Use the dir()
function to list all functions and variables available in a module.
dir(my_module)
displays a list of all functions, variables, and attributes inside my_module
.Modules make Python programs efficient, reusable, and organized by separating code into manageable files.
.....
.....
.....