Using Python Libraries
Using Python Libraries
SELF LEARNING
Enjoy programming. PRESENTATION.
Pro .pptx Format
gra
ama mm
zing ing
exp is an CHAPTER 4
erie
nce
.
USING
PYTHON
All images used in this presentation are
from the public domain
Modular Programing
Module 4
Module 3
One part of a
complex task is
called module.
Code reuse def fact(x=1):
f=1
for n in range(2,x+1):
The use of existing f *- n
code or modules in return f
further development
def add(a,b) :
is called 'code reuse' return a+b
def fibo(a=-1,b=1,n=10) :
if n==0:
I need this return
code again print(a+b)
in another fibo(b,a+b,n-1)
program.
Pi = 3.14
Modules, packages, and libraries are
all different ways to reuse a code.
Modules
Packages
libraries
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
What Is Module ?
Module is a collection
of functions, classes,
constants and other
statements.
Write the code on the board
in a fi le and save it with a
name with .py suffi x.
It becomes a module.
Collection of modules
are called package.
What Is Package ?
A group of modules saved in a
folder is called package.
Collection of modules
saved in a folder, are
called package.
What Is Library ?
Library is a collection of packages.
Suppose we write more packages about
anything. It will become a library. In
general, the terms package and library
have the same meaning.
ext ,
t n 5, 6
next ?
>>> int ( 3.14 ) The int() function returns
?
h a , 4,
,W ,3
OUTPUT : 3 integer value of given value.
, 9 1, 2
7, 8 hex,
The given float number is rounded In
round ( )
>>> round ( 3.65,0 )
to specified number of
OUTPUT : 4.0 decimal places.
oct(),hex() and bin() Functions.
Don't worry. you just count 1 to 20 using
for a in range(1,21) And use hex() and oct()
functions. The computer will do everything for you.
, 5 , In hex, 1, 2, 3, 4, 5, 6,
3, 4 ?
2, e x t 7, 8, 9, What next ?
, 1, tn
o ct ha Octal system has only 8 digits.
In 7, W They are 0 to 7. after 7, write 10
6,
for 8, 11 for 9, 12 for 10 etc.
Hexadecimal system has 16 digits.
They are 0 to 9 and 'a' for 10, 'b'
for 11... 'f' for 15. After 15, write
10 for 16, 11 for 17, 12 for 18 etc.
Do it in Python.
Prefix
.
>>> x split()
We get the list ['All', 'knowledge', 'is', 'within', 'us.']
split(x)
Wrong use x.split()
Right use
>>> x.split("A")
Fun?
We get the list ['M', 'VELIK', 'R', '']
string.join() joins a set of string into a single string.
J o i n t h e l i s t [ ' M a tt h e w ', ' K r i s h n a', ' Davi d ', ' R a m' ] i n t o a
s i n g l e s t r i n g l i k e ' M a tt h e w, K r i s h n a , Davi d , R a m'.
Na m e s s h o u l d b e j o i n e d b y t h e g l u e ‘ , '.
>>> ‘cobra’.replace(‘co’,’ze’)
zebra cobra becomes zebra
Importing Modules.
Modules such as math, cmath, random, statistics, urllib are
not an integral part of Python Interpreter. But they are
part of the Python installation. If we need them,
import them into our program and use them.
Name of
.
2. Place math (Namespace) before function name.
Object in that
Namespace Namespace
X = math.sqrt(25)
X = sqrt(25)
Showing Local Scope before and afrer imoprt
>>> locals() No math module in Local Scope.
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module
'builtins' (built-in)>}
>>> import math Error happened.
>>> help (math) Because you called
Help on built-in module math:
NAME help before
math ' Import Math‘
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
>>> math.factorial(5)
>>> math.factorial(-5)
Output : 120
>>> math.factorial(5.5)
fmod ( x,
fmodyfunction
) returns the remainder when x
is divided by y. Both x and y must be a number otherwise
error will occur.
= 2.5
>>> math.fmod(11.5,2.5)
5 1.5
modf (float
modfvalue)
() separates fractional and integer
parts from a floating point number. The result will be a
tuple. using multiple assignment, you can assign these 2
values in 2 variables.
Can you separate the fr action and
the integer parts of pi value?
>>> import math
>>> math.modf(math.pi)
Fractional part Integer part
Tuple data type (0.14159265358979312, 3.0)
Using Multiple Assignment
Like >>> a , b = math.modf(math.pi)
a,b,c = 10, 20, 30 a= 0.14159265358979312, b = 3
Importing statistics Modules.
Statistics module provides 23 statistical functions. Some of
them are discussed here. import statistics
Before using them. And call with “statistics.” prefix.
statistics.mean(list of calculate
mean() Nos) Arithmetic mean
(average) of data.
.
you to make random numbers. Don't forget to import random module
and use the function with randomprefix.
url = "https://www.facebook.com/"
webbrowser.open(url) opens mail
webbrowser.open("https://mail.google.com/")
opens youtube
webbrowser.open(“https://www.youtube.com/”)
>>> import webbrowser OUTPUT OF 2 LINE CODE
>>> webbrowser.open("https://www.slideshare.net/venugopalavarmaraja/")
es c od e Give any address (URL)here.
2 L in
WOW… only 2 Lines.
I want to open my
mail like this.
urllib is a package for working with URLs. It
contains several modules. Most important one is
'request'. So import urllib.request when working
with URLs. Some of them mentioning below..
Open a website denoted by URL for reading. It will return
Urllib.request.urlopen() a file like object called QUrl. It is used for calling following
functions.
QUrl.read() returns html or source code of the given url opened via
Urlopen().
QUrl.getcode() Returns the http status code like 1xx,2xx ... 5xx. 2xx(200)
denotes success and others have their meaning.
QUrl.geturl ()
Returns the url string.
import urllib.request
import webbrowser
u = "https://www.slideshare.net/venugopalavarmaraja/"
weburl = urllib.request.urlopen(u) Creating QUrl object(HTTP Request
html = weburl.read() Object)
code = weburl.getcode()
url = weburl.geturl() Calling Functions with QUrl Object
hd = weburl.headers
inf = weburl.info()
print("The URL is ", url)
print("HTTP status code = ", code )
Printing Data
print("Header returned ", hd )
print("The info() returned ", inf )
print("Now opening the url",url ) Opening Website
webbrowser.open_new(url)
Making our own modules
a t w e So far we have learned What are modules,
Wh o fa r?
rn ed s packages, and libraries? And familiarized
lea
with Standard Library. Libraries like Numpy,
Scipy, Tkinter, Matplotlib are not part of
Python Standard Libraries. So they
want to download and install. We
do It when we study 8th chapter.
Now we are going to learn
A module is a Python
file that contains a
collection of
functions, classes,
constants, and other
statements.
Creating Module
This is the file I wrote and saved.
File name is MYMOD.py.
What to do next.
Example 3
t u p t o x and
Coun with f
m u l t i p l y
1. Find factorial of a No
2. Find sum upto a No
t u p t o x and
Coun sum Import into a
d w i t h
a d new program.
Detailed Structure of a module.
Structure of a Module
DocString
1 (Documentation String)
Functions
2
Constants/Variables
3
Classes
4
Objects
5
6 Statements
Other
Create Module_01.py
Create Module (.py Files)
2 inside the folder
Create Module_02.py
Create __init__.py
What is the name of Creating MY_PACKAGE
the folder for the new
package?
e s am e Create a package called
h ave t h e.
Bo th n a m
“my_package"
to organize previously learned
modules
Creating Folfer.
Create folder anywhere using any method. But
Step 2. must be added to the System path
Creating MYMOD.py
>>> import os
MY
>>> os.mkdir Package
1 feet = 30 cm
inch = 2.5 cm MYMOD.py
SAVE IN
MY_PACKAGE Creating
CONVERSION.py.py
CONVESION.py
SAVE IN
MY_PACKAGE
o x an d
u p t
Creating MY_MATH.py Count h sum.
d d w i t
a
Create __init__.py
After creating modules, you also need to create __init__.py
import math.pi
‘Pi'
is an object defined in
the math module. Partial import is not
possible with the "Import" statement.
Importing multiple modules.
Multiple Modules can be imported with one import
statement. import <Module1>, <Module2>, …
import math
import math, random
import random
import my_package.MYMOD,my_package.MY_MATH
But it is not a
Using 2 standard style.
statements.
2 in 1 statements.
from … import statement
from module import component is another way
for importing modules or packages. Selected
components can be imported using this statement,
but it is not possible with the import statement.
import math.pi pi (pi = 3.1415) is a constant defined in math
module. You can’t import partial components.
Importing Modules
with new NAME
Namasthe