Tuesday, July 12, 2022

USING PYTHON LIBRARY / MODULES

Using Python Libraries

Introduction:

Real life application consists of huge lines of code and contains many feature that are common in between many application. Organizing these codes into groups has many benefits such as ease of maintainance and code reuse. python has many constucts like module, package and library to aid this idea

Terminology:

Module:Module is a file which contains various Python functions, global variables, classes and statements. It is simply just python file with .py extension with valid python code

Package:Package is a collection of modules i.e. a folder with many modules. It must contains an __init__.py file which signals the python interpreter to process the folder containing modules as a library. The __init__.py could be an empty file.

Library: Library is a collection of many packages

Modules in python:

Modules are used to categorize python code into smaller parts. A module is simply a python file where statements, classes, object, function, constants and variables are defined. Grouping similar code into a single file makes it easy to access, understand and use.

Advantages:

  • modules gives the ability to import the module functionality
  • modules usage facilitates resuability of code
  • it makes the code easier to understand and use
  • A module allows us to logically organize our python code
Important points
  • A module name is the name of the python file with .py extension.Eg: if file name is hello.py the module name is hello
  • The __name__ is a variable that hold the name of the module beigh referenced. If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name

Importing python module:

  • import keyword: import module_name1, module_name2
  • from keyword:this allows to import specific attributes, object, functions etc
In [2]:
# using import keyword
import math as m
import math as m, string as s
In [4]:
# using from keyword
from math import sqrt  #get specific function
from math import *     #get every thing from the module

NOTE: using the dir() on a a module, we can obtain names of everything defined inside the module

Module aliasing:

it is a process of giving a short name to a module and using a dot "." we are able to access all the attributes and object of the module.NOTE: naming an alias follows the identifier decleration rules

syntax: import module_name as alias

In [5]:
import numpy as np # Here np is a alias

Namespace in python:

In python a name is an identifier, that is used to access a python object. A Namespace in python is a collection of names. It helps distinguish between diffrent section of a program, so its a practical approach to define the scope and it helps to avoid name conflicts

Note:

  • Python implements namespace in the form of dictionaries. It maintains a name to object mapping where names act as keys and object as values.
  • In python there are three types of namespaces-Global, Local and Built-in
  • When we call a function, a local namespace is created for all the names in the function
  • A module has a global Namespace
  • A built-in namespace encloses local and global namesapce

Package/Library:

A package is just a folder containing one or more module(i.e. python file) and a __init__py file. __init__.py is simply a file that is used to consider the directories on the disk as package of python. It is basically used to initialize the python package

Example:

if in folder arithmetic we have two python file addition.py and multiplication.py, now we add a __init__.py file in this folder then this folder becomes a package.Now we can use the following code to access the module in this folder

from arithmetic import addition as ad

Standard python libraries:

Python comes a library of standard modules i.e. they dont need to installed as like numpy, pandas etc and can be simply imported and used.

math module: some of the function of this module are listed below

  1. ceil(x): returns the smallest integer that is greater than or equal to x
In [2]:
import math as m
print(m.ceil(3.4))
4
  1. floor(x): returns the largest integer that is less than or equal to x
In [3]:
import math as m
print(m.floor(3.4))
3
  1. pow(x,y): It returns the value(in float) of x raised to y, where x and y are numbers
In [5]:
import math as m
print(m.pow(2,3))
8.0
  1. sqrt(x): Returns the square root of x in float
In [6]:
import math as m
print(m.sqrt(25))
5.0

random module: Some of the commonly used function are listed below:

  1. randrange(x): generate an integer between 0 and upper arguments x
In [5]:
import random as r
print(r.randrange(20))
15
  1. random(): generates a random number from 0 to 1
In [10]:
import random as r
print(r.random())
0.7284804072482647
  1. randint(a,b): generates a random number between the a and b both inclusive
In [11]:
import random as r
print(r.randint(10,15))
11
  1. choice(sequence): used to get a random selection froma sequence like list, tuple or string
In [10]:
import random as r
print(r.choice([10,25,48,43,23]))
23
  1. shuffle(list): user to shuffle or swap the items of a list. the shuffle is done inplace so the orginal list gets over written
In [15]:
import random as r
ls=[10,20,30,40,50,60,70]
print(ls)
r.shuffle(ls)
print(ls)
[10, 20, 30, 40, 50, 60, 70]
[50, 10, 30, 70, 60, 40, 20]

datetime: this modules handles the extraction and formatting of data and time variables

today() function that belongs to the date class and prints the current date

In [1]:
import datetime as d
dt=d.date.today()
print(dt)
2020-09-05

we can extract the year, month and date from the above date by using the year, month and day attribute

In [21]:
print(dt.year)
2020
In [22]:
print(dt.month)
9
In [23]:
print(dt.day)
2
In [3]:
dir(d.datetime)
Out[3]:
['__add__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__ne__',
 '__new__',
 '__radd__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rsub__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 'astimezone',
 'combine',
 'ctime',
 'date',
 'day',
 'dst',
 'fold',
 'fromisocalendar',
 'fromisoformat',
 'fromordinal',
 'fromtimestamp',
 'hour',
 'isocalendar',
 'isoformat',
 'isoweekday',
 'max',
 'microsecond',
 'min',
 'minute',
 'month',
 'now',
 'replace',
 'resolution',
 'second',
 'strftime',
 'strptime',
 'time',
 'timestamp',
 'timetuple',
 'timetz',
 'today',
 'toordinal',
 'tzinfo',
 'tzname',
 'utcfromtimestamp',
 'utcnow',
 'utcoffset',
 'utctimetuple',
 'weekday',
 'year']
In [10]:
dt.day
Out[10]:
5
In [23]:
day=dt.strftime("%b")
print(day)
Sep

String: This module contains constant, function etc for string manipulation

  1. Constants present in string module
In [1]:
import string as sr

# string module constants
print(sr.ascii_letters)
print(sr.ascii_lowercase)
print(sr.ascii_uppercase)
print(sr.digits)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
  1. function present in string module
In [5]:
#string.capwords  # 1st letter of every word gets capitalized

s = '  computer science is cool'
print(sr.capwords(s))  
Computer Science Is Cool

Reference:

  1. NCERT for class CS
  2. Journal Dev
Share: