Python Day- 8
Python Day- 8
Importing and using modules, Writing your own modules, Exploring standard library
modules, Understanding packages and dir() function. Problems on above concepts.
● 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.
1. Basic Import:
import math
import math as m
Note: Avoid using this for large modules, as it can lead to name conflicts.
Example
File: mymodule.py
PI = 3.14159
Using the Module
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
Examples:
import os
sys Module
Examples:
import sys
Examples:
random Module
Examples:
import random
math Module
Examples:
import math
Understanding Packages
What is a Package?
Creating a Package
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
What is dir()?
● The dir() function returns a list of attributes and methods available in a module, class,
or object.
Example:
import math
import mymodule
● Lists the names of all variables, functions, and objects in the current scope.
Example:
a = 10
b = "hello"
print(dir()) # Output: ['a', 'b', ...]
○ Create a directory.
○ List all files in the directory.
○ Delete the created directory.
4. Use the random module to: