Python Modules
A module is a file containing Python definitions and statements. Modules are used to break down large programs into small manageable and organized files.
Example 1: Creating and Using a Module
Create a module named greetings.py
and import it.
# greetings.py
def say_hello(name):
print(f"Hello, {name}!")
In another file:
# main.py
import greetings
greetings.say_hello("Karthick AG")
Hello, Karthick AG!
Example 2: Using from
and import
Import specific functions from a module.
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
In another file:
# main.py
from math_operations import add
result = add(10, 5)
print("Result:", result)
Result: 15
Example 3: Renaming Modules Using as
Import a module with an alias.
# Importing with alias
import math as m
print("Square root of 16:", m.sqrt(16))
Square root of 16: 4.0
Example 4: Built-in Modules
Use Python's built-in modules like datetime
and random
.
# Using datetime module
import datetime
today = datetime.date.today()
print("Today's date:", today)
Today's date: 2023-10-05
Example 5: Installing and Using External Modules
Install and use the requests
module to make HTTP requests.
# Install using pip
# pip install requests
# Using requests module
import requests
response = requests.get("https://api.github.com")
print("Status Code:", response.status_code)
Status Code: 200
Example 6: Exploring Module Search Path
Print the list of directories where Python looks for modules.
# Module search path
import sys
print("Module Search Path:")
for path in sys.path:
print(path)
Output List of directories
Explanation: Modules help organize code and promote code reusability. You can create your own modules, use built-in modules, or install external modules using package managers like pip
.