A Module is a file containing Python code, such as functions, variables, and classes, that can be reused in other Python programs.
Modules help organize code and make it reusable.
Creating a Module
Create a Python file named mymodule.py.
mymodule.py
def greet(name):
print("Hello", name)
Importing a Module
Use the import keyword to use a module.
Example
import mymodule
mymodule.greet("John")
Output:
Hello John
Import Specific Functions
You can import only the required function from a module.
Example
from mymodule import greet
greet("Alice")
Output:
Hello Alice
Import with Alias
The as keyword creates a shorter name for the module.
Example
import mymodule as mm
mm.greet("Bob")
Output:
Hello Bob
Import Multiple Functions
Example
from mymodule import greet, add
Import All Functions
Use * to import everything from a module.
Example
from mymodule import *
Using
*is generally not recommended because it can make code harder to understand.
Access Module Variables
mymodule.py
company = "Tech58"
Example
import mymodule
print(mymodule.company)
Output:
Tech58
Built-in Modules
Python provides many built-in modules that can be imported directly.
Example
import math
print(math.sqrt(25))
Output:
5.0
Why Use Modules?
- Reuse code across multiple projects.
- Organize large applications.
- Reduce duplicate code.
- Improve code readability and maintenance.
Summary
- A module is a Python file containing reusable code.
- Use
importto include a module. - Use
from module import functionto import specific functions. - Use
asto create an alias. - Modules can contain functions, variables, and classes.
- Python provides many built-in modules.