Unit-VI-Introduction-to-Libraries - And-Modules (NEP)
Unit-VI-Introduction-to-Libraries - And-Modules (NEP)
(23DCE2101)
import math #You need to put this command,`import` keyword along with the name of the module you want to import
num = 4
print(math.sqrt(num)) #Use dot operator to access sqrt() inside module "math"
Output:
2
# my_rand_int.py Output:
import random 20
for i in range(10): 8
15
print(random.randint(1, 25))
18
11
# dateModule.py 20
23
import datetime
13
x = datetime.datetime.now() 6
print(x) 9
Output:
2024-12-05 22:17:10.382522
#Year-month-date HH:MM:SS.microseconds
Writing Modules in Python
• Writing a module is just like writing any other Python file. And saving this file with .py
extension.
#calculation.py
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
#TestModule1.py
import calculation #Importing calculation module
print(calculation.add(1,2)) #Calling function defined in add module.
print(calculation.sub(7,3))
Output:
3
4
Additional Ways to Import Modules in Python
There are more ways to import modules:
1) from .. import statement:-
from calculation import add
print(add(1,2))
#You can now access it directly without using the module name.
from calculation import add,sub # You can import multiple attributes
Example:
In this example, we are creating a two-dimensional array that has the rank of 2 as it
has 2 axes.
The first axis(dimension) is of length 2, i.e., the number of rows, and the second
axis(dimension) is of length 3, i.e., the number of columns. The overall shape of the
array can be represented as (2, 3)
# Program: numpy_array-example.py
import numpy as np
#Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
ser = pd.Series(data)
print("Pandas Series:\n", ser)
Pandas DataFrame
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and
columns).
Creating DataFrame
Pandas DataFrame is created by loading the datasets from existing storage (which
can be a SQL database, a CSV file, or an Excel file).
Pandas DataFrame can be created from lists, dictionaries, a list of dictionaries, etc.
# list of strings
lslst = ['Python', 'Language', 'is','the','easiest', 'Language', 'I', 'studied']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)