A module in Python is a file containing Python code, such as functions, classes, or variables, that you can reuse in other Python programs. Modules help organize code into manageable and reusable components, promoting modularity and code reuse.
1. What is a Python Module?
- A Python module is simply a file with a
.pyextension that contains Python code. - Modules can include:
- Variables
- Functions
- Classes
- Constants
2. Types of Python Modules
- Built-in Modules: Predefined modules provided by Python, such as
math,os,random, etc. - User-defined Modules: Custom modules created by you.
- Third-party Modules: Modules installed via package managers like
pip, such asnumpyorpandas.
3. Using a Module
Importing a Module
To use a module, you import it into your program using the import keyword.
Example:
import math
print(math.sqrt(16)) # Outputs: 4.0
4. Built-in Modules
Python provides a variety of built-in modules. Here are a few commonly used ones:
4.1 Math Module
The math module provides mathematical functions.
Example:
import math
print(math.pi) # Outputs: 3.141592653589793
print(math.factorial(5)) # Outputs: 120
4.2 Random Module
The random module is used for generating random numbers.
Example:
import random
print(random.randint(1, 10)) # Outputs: A random number between 1 and 10
print(random.choice(['apple', 'banana', 'cherry'])) # Outputs: A random fruit
4.3 OS Module
The os module provides functions to interact with the operating system.
Example:
import os
print(os.name) # Outputs: The name of the operating system
print(os.getcwd()) # Outputs: Current working directory
5. User-Defined Modules
You can create your own module by writing Python code in a .py file.
5.1 Creating a Module
1. Create a file named my_module.py with the following content:
# my_module.py
def welcome(name):
return f"Hello, {name}!"
pi = 3.14159
2. Import and use it in another Python file:
# main.py
import my_module
print(my_module.welcome("Infovistar")) # Outputs: Hello, Infovistar!
print(my_module.pi) # Outputs: 3.14159
5.2 Using from ... import Syntax
You can import specific functions or variables from a module.
Example:
from my_module import greet
print(welcome("Junaid")) # Outputs: Hello, Junaid!
5.3 Renaming a Module
You can rename a module using the as keyword.
Example:
import my_module as mm
print(mm.welcome("Arsheen")) # Outputs: Hello, Arsheen!
