Python Day- 8
(RECAP OF PREVIOUS DAY)
Importing and using modules, Writing your own modules, Exploring standard library
modules, Understanding packages and dir() function. Problems on above concepts.
Importing and Using Modules
What is a Module?
● A module is a file containing Python code (functions, variables, classes) that can be
reused in other Python programs.
● Python has built-in modules, third-party modules, and user-defined modules.
How to Import a Module
1. Basic Import:
import math
# Using the module
result = math.sqrt(16)
print(result) # Output: 4.0
2. Import Specific Functions or Variables:
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
3. Import with an Alias:
import math as m
print(m.sqrt(36)) # Output: 6.0
4. Import All from a Module:
from math import *
print(sin(0)) # Output: 0.0
Note: Avoid using this for large modules, as it can lead to name conflicts.
Writing Your Own Modules
Steps to Create a Module
1. Create a .py file with functions, variables, or classes.
2. Import this file into another Python program.
Example
File: mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
Using the Module
# Importing the module
import mymodule
# Using functions and variables from the module
print(mymodule.add(5, 3)) # Output: 8
print(mymodule.subtract(10, 4)) # Output: 6
print(mymodule.PI) # Output: 3.14159
Import Specific Functions
from mymodule import add, PI
print(add(7, 2)) # Output: 9
print(PI) # Output: 3.14159
Tips for Writing Modules
● Use meaningful names for your functions and variables.
● Add documentation for each function.
● Use if __name__ == "__main__": to include test code that won’t run when the
module is imported.
Example with Test Code:
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Division by zero error"
return a / b
if __name__ == "__main__":
print(multiply(4, 5)) # Output: 20
print(divide(10, 2)) # Output: 5.0
Exploring Standard Library Modules
Python provides a rich set of built-in modules known as the standard library. Below are some
commonly used modules:
os Module
● Used for interacting with the operating system.
Examples:
import os
# Get the current working directory
print(os.getcwd())
# List files and directories
print(os.listdir())
# Create a new directory
os.mkdir("new_folder")
sys Module
● Provides access to system-specific parameters and functions.
Examples:
import sys
# Get command-line arguments
print(sys.argv)
# Exit the program
sys.exit()
datetime Module
● Used for working with dates and times.
Examples:
from datetime import datetime
# Get the current date and time
now = datetime.now()
print(now)
# Format the date
print(now.strftime("%Y-%m-%d %H:%M:%S"))
random Module
● Used for generating random numbers.
Examples:
import random
# Generate a random number between 1 and 10
print(random.randint(1, 10))
# Pick a random choice from a list
print(random.choice(["apple", "banana", "cherry"]))
math Module
● Provides mathematical functions.
Examples:
import math
# Calculate the square root
print(math.sqrt(49))
# Calculate the sine of a number
print(math.sin(math.pi / 2))
Understanding Packages
What is a Package?
● A package is a collection of related modules organized into a directory with a special
__init__.py file.
● The __init__.py file can be empty or used to initialize the package.
Creating a Package
1. Create a directory with a meaningful name (e.g., mypackage).
2. Add an empty __init__.py file to the directory.
3. Add module files to the package directory.
Example Structure:
mypackage/
__init__.py
module1.py
module2.py
File: mypackage/module1.py
def greet(name):
return f"Hello, {name}!"
File: mypackage/module2.py
def square(n):
return n * n
Using the Package
from mypackage import module1, module2
print(module1.greet("Alice")) # Output: Hello, Alice!
print(module2.square(5)) # Output: 25
Understanding the dir() Function
What is dir()?
● The dir() function returns a list of attributes and methods available in a module, class,
or object.
Example:
import math
# List all attributes and methods in the math module
print(dir(math))
Using dir() for Custom Modules
import mymodule
# List all attributes and methods in the custom module
print(dir(mymodule))
Using dir() Without Arguments
● Lists the names of all variables, functions, and objects in the current scope.
Example:
a = 10
b = "hello"
print(dir()) # Output: ['a', 'b', ...]
List of programs to practice (Home work)
1. Write a custom module mathutils.py with functions for:
○ Calculating factorial of a number.
○ Checking if a number is prime.
2. Create a package stringutils with modules:
○ string_operations.py: Functions to reverse a string and check for
palindrome.
○ case_operations.py: Functions to convert a string to uppercase and
lowercase.
3. Write a program to explore the os module:
○ Create a directory.
○ List all files in the directory.
○ Delete the created directory.
4. Use the random module to:
○ Generate 10 random numbers between 1 and 100.
○ Simulate rolling a dice.
5. Create a package mathpackage with the following modules:
○ arithmetic.py: Functions for addition, subtraction, multiplication, and division.
○ geometry.py: Functions to calculate the area of a circle and rectangle.
6. Write a program to:
○ Import and explore the sys module.
○ Print the Python version and platform details.
7. Write a function in a custom module that:
○ Reads a file and counts the frequency of each word.
8. Use the dir() function to list all available functions in:
○ The random module.
○ A custom module you create.
9. Write a script that uses the datetime module to:
○ Print the current date and time.
○ Calculate the number of days between two dates.
10. Create a package utilities with:
● An __init__.py file that imports specific functions from its modules.
● Modules for math operations, string operations, and date operations.