Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Python Modules and Library: Purpose: Advantage

The document discusses Python modules, libraries and built-in functions. It provides examples of standard Python modules like math, random and statistics. It explains that a module is a collection of related variables and functions and a library is a collection of modules for a specific purpose. The document then lists some common functions from the math, random and statistics modules along with their purpose and examples. It also discusses built-in functions in Python for numeric conversions, sequence operations and more.

Uploaded by

Tanisha Jena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Python Modules and Library: Purpose: Advantage

The document discusses Python modules, libraries and built-in functions. It provides examples of standard Python modules like math, random and statistics. It explains that a module is a collection of related variables and functions and a library is a collection of modules for a specific purpose. The document then lists some common functions from the math, random and statistics modules along with their purpose and examples. It also discusses built-in functions in Python for numeric conversions, sequence operations and more.

Uploaded by

Tanisha Jena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

PYTHON MODULES AND LIBRARY

Module is a collection of variables, functions, classes, object etc related to a particular type of entity.
Purpose : Implement modularity i.e. partition a program into several well individual components.
Advantage : Reduces complexity of development and further modification

Library is a collection of modules for a specific purpose or application.

Example:

Python Libraries

Python standard
library SciPy Library NumPy Library Matplotlib
Library

math random numpy pyplot


module module module module

floor() random() array() plot()


pow() randint() linspace() xlabel()
sin() trunc() show()

Python Built-in functions - numeric

Function Argument(s) Ret Purpose Example


Type
int(S) S is a string of only int Convert to decimal int("1365") = 1365, int(1365.65) = 1365
digits or a float integer # int("63.215"), int("6E.2A") gives
ERROR
oct(X) X is an integer str Convert to Octal oct(100) = '0o144', oct(-100) = '-0o144'
integer
hex(X) X is an integer str Convert to hex(-100) = '-0x64', hex(100) = '0x64'
Hexadecimal
integer
float(S) S is a string of only float Convert to float float("63.12") = 63.12, float(10) = 10.0
digits and ‘.’ or an
int
round(x,n) x is float, n is float Round off x to n round(63.895632,3) = 63.896
optional / int digits after decimal round(63.895632) = 64
point, otherwise int
Python Built-in functions for sequence

Function Purpose Example


str(x) Convert any data type to string str(True) = 'True', str(100) = '100'
list(x) Convert string/tuple to list list("Hello") = ['H', 'e', 'l', 'l', 'o']
tuple(x) Convert string/list to tuple tuple("Hello") = ('H', 'e', 'l', 'l', 'o')
tuple(['H', 'e', 'l', 'l', 'o']) = ('H', 'e', 'l', 'l', 'o')
eval() Convert to appropriate data type eval(“Hello”) → str
considering syntax in input string eval("[8,9,6]") → list

Data sequence Example of functions on data sequence


string join(), split(), replace(), lower(), isupper(), isdigit(), capitalize(), find() etc
list append(), extend(),remove(), index() insert(), pop(), clear(), count(), sort() etc
tuple index(), count(), index() etc
dictionary get(), items(), keys(), values(), update(), clear(), pop() etc
General len(S), max(S), min(S)

math library functions (import math)

Sl. Function Name Ret. Purpose Example


No. Type
1 sin(float), float Trigonometrical math.sin(math.pi/2) = 1.0
cos(float), functions accepts angle math.cos(0) = 1.0
tan(float) in radian math.tan(0) = 0.0
2 ceil(float) int Nearest integer above math.ceil(9.2)=10, math.ceil(9)=9
math.ceil(-9.2)=-9, math.ceil(-9)= -9
3 floor(float) int Nearest integer below math.floor(9.2) = 9, math.floor(9) = 9
math.floor(-9.2) = -10, math.floor(-9) = -9
4 fabs(float) float Absolute value math.fabs(-9.3) = 9.3 math.fabs(9.3) = 9.3
5 sqrt(float) float Square root of a math.sqrt(25) = 5.0
positive real number math.sqrt(-25) # ERROR as Imaginary
6 pow(float, float) float Ab where A is 1st, b is math.pow(4, 3) = 64.0,
2nd parameter. math.pow(4.2, 3.2) = 98.718
Result cannot be math.pow(-4.2, 3) = -74.088
imaginary number. math.pow(-4, -3) = -0.015625
math.pow(-25,0.5) # ERROR as Imaginary
Sl. Function Name Ret. Purpose Example
No. Type
7 exp(float) float ex where x is parameter math.exp(1) = 2.718281828459045
8 log(float) float Natural log of 1st arg, math.log(16) = 2.772588722239781
nd
log(float, float) 2 arg base is optional. math.log(16,2.1)=3.736958035521297
Both args must be +ve. math.log(16,2) = 4.0
math.log(16,-2), math.log(-16), math.log(0)
produces DOMAIN ERROR
9 log10(float) float Log base 10 of positive math.log10(1000)=3.0
float math.log10(0.001)=-3.0
10 degrees(float) float Input angle in radians math.degrees(3.15) = 180.48170546620932
and returns degree math.degrees(-3.15) = -180.48170546620932
11 radians(float) float Input angle in degrees math.radians(90) = 1.5707963267948966
and returns radians math.radians(-90) = -1.5707963267948966

random library functions (import random)

Sl. Function Name Ret. Purpose Example


No. type
1 random() float 1. Generate a real number N, random.random() =
0.0 ≤ N <1.0 0.8579308403684683

2. Random real number random.random() =


between two values a and b 0.7908206309279567
= N * (b-a) + a
random.random()*(30-10) + 10
= 18.69140037731256

random.random()*(30-10) + 10
=29.70674695914648
2 randint(int, int) int randint(a,b) generates an random.randint(10,30) = 23
integer N between a and b,
a≤N≤b random.randint(-30,10) = -29
3 randrange(int,int,int) int 1. randrange(start,stop,step) random.randrange(10,30,5) = 25
generate an integer N between # start = 10, stop = 30, step = 5
start and stop-1 with a step
value step, random.randrange(10,30) = 17
start ≤ N < stop # start = 10, stop = 30, step = 1

2. start is optional by default 0, random.randrange(30) = 9


step is optional by default 1. # start = 0, stop = 30, step = 1
Statistics library functions (import statistics)

These functions works on sequence data types like list and tuple
Sl. Function Name Ret. Purpose Example
No. type
1 mean(sequence) float mean/average value statistics.mean((10, 50.5, 30, 40.5)) = 32.75
2 median(sequence) float middle value in the statistics.median([10, 50, 30, 40]) = 35.0
sequence of # Average of 2 if no. of elements is even
ascending /
descending order of statistics.median([10, 50, 90, 30, 40]) = 40
values. #Only one in case of odd no. of elements

statistics.median(['a','c','p','x','z']) = 'p'
#statistics.median(['a','c','p','x','z','m']) ERROR
as middle cannot be calculated
3 mode(sequence) float Most frequent statistics.mode(['a','c','p','a','x','z','m','a'])='a'
element in a statistics.mode([10, 50, 40, 30, 40, 50, 40])=40
sequence. If multiple
elements have same #ERROR
highest frequency statistics.mode(['a','c','p','c','a','x','c','z','m','a'])
then ERROR. as a →3 and c → 3
statistics.mode([10, 50, 10, 30, 40, 30])
as 10 → 2 and 30 → 2

Import modules in program:

1. Import Single module – import math


print(math.sqrt(25)) #Output = 5

2. Import Multiple modules - import math, random


x =random.randint(2, 5) #x = 2
print(math.pow(x,3)) #Ouput = 8.0

3. Import all objects from a module – from math import *


<module prefix Not Required> print(sqrt(25)) #Output = 5

4. Import selective object from module -from math import pi, sqrt
<module prefix Not Required> print(round(sqrt(pi),3)) # Output = 1.772

5. Import and Rename module - import math as m


print(m.floor(m.pi)) #Output = 3
STRUCTURE OF A PYTHON MODULE

 docstrings – tripple quoted comments used for documentation


 Variables / Constants – define label for data.
 Classes – customized data type with data members and function related to an entity
 Objects – Implementation / instance of class which is allocated specific memory location
 Statements - instructions for execution
 Functions – group of statements for specific operation

DEFINE A PYTHON MODULE

#INR_USD.py

""" Conversion function between Indian Rupee and US Dollar """

#Functions

def toUSD(INR):
""" Returns: INR converted to USD """
return round(INR * 0.013, 2)

def toINR(USD):
""" Returns: USD converted to INR """
return round(USD * 75.38, 2)

# Constants

Base_USD = 75.38
""" 1 USD = 75.38 INR as on 30.03.2020 """

Base_INR = 0.013
""" 1 INR = 0.013 USD as on 30.03.2020 """

'''
OUTPUT:
>>> import INR_USD

>>> help(INR_USD)

Help on module INR_USD:

NAME
INR_USD - Conversion function between Indian Rupee and US Dollar
FUNCTIONS

toINR(USD)
Returns: USD converted to INR

toUSD(INR)
Returns: INR converted to USD

DATA

Base_INR = 0.013
Base_USD = 75.38

FILE

/home/sonam/INR_USD.py

'''

IMPORT MODULE IN A PYTHON PROGRAM

import INR_USD as Cur

print("1 Rupee = ", Cur.Base_USD, "USD")


print("1 USD = ", Cur.Base_INR, "Rupees")

print("Press 'I' to input Indian Currency!")


print("Press 'U' to input US Currency!")
choice = input("Enter your choice : ")

if choice.upper()[0] == 'I':
inr = float(input("Enter Amount of Rupee : "))
usd = Cur.toUSD(inr)
print("The equivalent amount in US currency is = ", usd, " USD")

elif choice.upper()[0] == 'U':


usd = float(input("Enter Amount of US dollar : "))
inr = Cur.toINR(usd)
print("The equivalent amount in Indian currency is = ", inr, " Rupees")

else:
print("Error in selection of Menu!!!")
'''
Output:

1 Rupee = 75.38 USD


1 USD = 0.013 Rupees
Press 'I' to input Indian Currency!
Press 'U' to input US Currency!
Enter your choice : I
Enter Amount of Rupee : 500
The equivalent amount in US currency is = 6.5 USD
>>>
======================== RESTART: /home/sonam/test.py ========================
1 Rupee = 75.38 USD
1 USD = 0.013 Rupees
Press 'I' to input Indian Currency!
Press 'U' to input US Currency!
Enter your choice : U
Enter Amount of US dollar : 2
The equivalent amount in Indian currency is = 150.76 Rupees
'''

PACKAGE

Package is a collection of Python modules under common namespace.


A single directory contains different modules along with some special files (e.g. - __init__.py for
importable python package)
A Library can have multiple packages or sub packages.

PROCEDURE FOR CREATING PACKAGE

Design basic structure of package

Create directory structure having folders with the


names of packages and sub packages

Create __init__.py files in package or sub package folders

Associate package to Python site-package folder by using


sys.path attribute for PYTHONPATH
__________

You might also like