You are on page 1of 101

SELF LEARNING

PRESENTATION.
PDF Format

CHAPTER 4

All images used in this presentation


are from the public domain
Friends,
Module 1 assigning to Aswin
Module 3 and 5 goes to Naveen
Module 4 to Abhishek, 2 to Sneha
and .., Abhijith will lead you.
I need this
code again
in another
program.
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.

Look at the board. There are


some functions, classes, constant
and some other statements.
Absolutely this is a module.

Module is a collection
of functions, classes,
constants and other
statements.
Write the code on the board
in a file and save it with a
name with .py suffix.
It becomes a module.
Can you try your Yes 2 . I want to write
own modules ? some more module
files.

Good. That is Package.


A group of modules saved in a
folder is called package.

I want a package contains


my own modules.

Collection of modules
saved in a folder, are
called package.
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.
PYTHON has rich libraries.
,
.
The Python Standard Library contains
built-in data, functions, and many modules.
All are part of the Python installation.
Basic Contents of Standard Library.
and

Built-in
Data,
functions
+ more

Module to import
1. Math module
2. Cmath module
3. Random module
4. Statistics module
5. Urllib module
print ( "10 + 20 = ", 10 + 20 ) print(), input(),
10 + 20 are basic operation.
print ( "Cube of 2 is ", 2 ** 3 ) No need to import anything.
sqrt () and pow () are defined in
Math module. So need to
import math import math modules.

print ("Square root of 25 is ", math.sqrt(25) )


print ("Cube of 2 is ", math.pow(2,3) )

We use the
Statement to import other
modules into our programs.
Examples of Built-in Function.

hex ( Integer Argument ) Accept an integer in any system and returns


>>> hex ( 10 ) its Hexadecimal equivalent as string.
OUTPUT : ‘0xa’
oct ( Integer Argument )
Accept an integer in any
>>> oct ( 10 ) system and returns its
OUTPUT : ‘0o12’ octal equivalent as string.
In oct, 1, 2, 3, 4,
int ( string / float Argument ) 5, 6, 7, What
next ?
>>> int ( 3.14 ) The int() function returns
OUTPUT : 3 integer value of given value.
round ( ) The given float number is rounded
>>> 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.

Octal system has only 8 digits.


They are 0 to 7. after 7, write
10 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.
print ("Numbering System Table")
print("column 1: Decimal System, col2 : Octal, col3: Hex, col4: Binary")
for a in range(1,25):
CODE
print(a, oct(a), hex(a), bin(a) )
Numbering System Table 16 0o20 0x10 0b10000
column 1 :Decimal System, col2 : Octal, 17 0o21 0x11 0b10001 OUTPUT
col3: Hex, col4: Binary 18 0o22 0x12 0b10010
1 0o1 0x1 0b1 19 0o23 0x13 0b10011
2 0o2 0x2 0b10 20 0o24 0x14 0b10100
3 0o3 0x3 0b11 21 0o25 0x15 0b10101
4 0o4 0x4 0b100 22 0o26 0x16 0b10110
5 0o5 0x5 0b101 23 0o27 0x17 0b10111
6 0o6 0x6 0b110 24 0o30 0x18 0b11000

oct() convert given value to octal system.


hex() convert given value to Hexadecimal system.
bin() convert given value to Binary system.
int () and round () Function.
int ( float/string Argument ) The int() function returns integer value
>>> int ( 3.14 ) (No decimal places) of given value. The given
OUTPUT : 3 value may be an integer, float or a string like “123”
>>> int (10/3)
OUTPUT : 3
>>> int( “123” )
OUTPUT : 123

round (float , No of Decimals)


>>> round ( 3.65 , 0 )
OUTPUT : 4.0
The given float number is rounded to specified
number of decimal places. If the ignoring number is
above .5 ( >=.5) then the digit before it will be added by 1.
Join the words “lion”, “tiger” and
“leopard” together.

Replace all "a" in “Mavelikkara” with "A".

Split the line 'India is my motherland'


into separate words.

“anil” + “kumar” = “anil kumar”,


“anil” * 3 = “anilanilanil”. These are
the basic operations of a string.
string.split() function splits a string into a list.

>>> x = "All knowledge is within us.“


Prefix
>>>
We get the list ['All', 'knowledge', 'is', 'within', 'us.']
Wrong use Right use
>>> x = "Mathew,Krishna,David,Ram"
>>> x.split( “,” )
We get the list ['Mathew', 'Krishna', 'David', 'Ram']

>>> x = "Mathew\nKrishna\nDavid\nRam" Cut when


>>> x.split( “\n” ) you see “\n“.
We get the list ['Mathew', 'Krishna', 'David', 'Ram']

>>> x = "MAVELIKARA" "MAVELIKARA" Is it


>>> x.split("A")
Fun?
We get the list ['M', 'VELIK', 'R', '']
string.join() joins a set of string into a single string.

Delimit string.join ( collection of string )

“,”. join ( [‘Item1’, ‘Item2’, ‘Item3’] )


‘Item1’ 1 2
‘Item1,Item2’ 3
End Item1,Item2,Item3
>>> a = ['Matthew', 'Krishna', 'David','Ram']
>>> ",".join(a) OUTPUT : 'Matthew,Krishna,David,Ram'
Do it in Python.
>>> a = ['Trissur','Ernakulam','Kottayam', 'Mavelikara' ]
>>>> "->".join(a)
'Trissur->Ernakulam->Kottayam->Mavelikara'
replace () Function. replace () Function.
Can you change function replaces a phrase with
zebra to cobra? another phrase.
string.replace(what, with, count )
What to replace?
Replace with what?
How many replacement is
needed.(optional)

>>> ‘zebra’.replace(‘ze’,’co’)
cobra zebra becomes cobra

>>> ‘cobra’.replace(‘co’,’ze’)
zebra cobra becomes zebra
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.

We use "Import” statement to import


Other modules into our programs.
It has many forms. We will learn in detail later.
Syntax is import < module Name >

E.g. import math


import random
Python does a series of actions when you import module,
They are
The code of importing modules is interprets
and executed.

Defined functions and variables in the


module are now available.

A new namespace is setup for importing modules.


A namespace is a dictionary that contains the names and definitions
of defined functions and variables. Names are like keys and
definitions are values. It will avoid ambiguity between 2 names.
I teach 2 Abhijit. one is in class XI-B and
other is in class XII-A. How can I write
their name without ambiguity.

.
class XI-B Abhijit .
class XII-A Abhijit
Are not Ashwin in 12.B?
Your Reg. No 675323.

No Sir, Check
the list of 12.A
An object (variable, functions
Google K.M. Abraham. etc.) defined in a namespace is
associated with that
Who is കുഴിക്കാലായിൽ namespace. This way, the
അബ്രഹാാം(K M Abraham) same identifier can be defined
He is a member of in multiple namespaces.
കുഴിക്കാലായിൽ Object in that
Name of
family. Namespace Namespace
>>> math .
Output : 5
>>> math.pi
Output :3.141592653589793
math
math and cmath modules covers many mathematical
functions.
and .
More than 45 functions and 5 constants are defined in it.
The use of these functions can be understood by their
name itself.

1. import math
2. Place (Namespace) before function name.
Name of Object in that
Namespace Namespace
X = sqrt(25)
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module
'builtins' (built-in)>}

>>> import math


>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module
'builtins' (built-in)>, 'math': <module 'math' (built-in)>}
>>>
>>> help(math)
Traceback (most recent call last): File "<pyshell#1>", line 1, in <module>
help(math)
NameError: name 'math' is not defined
>>> import math
>>> help (math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
import math FUNCTIONS.
The value without –ve / +ve symbol is called
absolute value. Both functions give absolute value, while fabs () always give a float
value, but abs () gives either float or int depending on the argument.
Abs() is built-in
>>> abs(-5.5) >>> abs(5)
function.
Output : 5.5 5
>>> math.fabs(5) >>> math.fabs(5.5)
Output : 5.0 5.5

Returns factorial value


of given Integer. Error will occur if you enter a -ve or a float value.
Right use Wrong use

>>> >>> math.factorial(-5)


Output : 120 >>> math.factorial(5.5)
fmod function returns the
remainder when x is divided by y. Both x and y must be a
number otherwise error will occur.

What is the remainder when


10.32 is divided by 3? >>> import math
𝟏𝟎.𝟑𝟐
=3×3=9 >>> math.fmod(10.32,3)
𝟑
𝑟𝑒𝑚𝑎𝑖𝑛𝑖𝑛𝑔 1.32 1.32
What is the remainder when
11.5 is divided by 2.5? >>> import math
>>> math.fmod(11.5,2.5)
1.5
modf () 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 fraction and
the integer parts of pi value?
>>> import math
>>> math.modf(math.pi)
Fractional part Integer part
Tuple data type (0.14159265358979312, 3.0)

>>> a , b = math.modf(math.pi)
a= 0.14159265358979312, b = 3
Statistics module provides 23 statistical functions. Some of
them are discussed here.
Before using them. And call with “statistics.” prefix.

mean() calculate
Arithmetic mean (average) of data.

>>> import statistics Mean is


>>> statistics.mean( [1,2,3,4,5] ) calculated as
Sum of Values
Output : 3 Count of Values
>>> statistics.mean( [1,2,3,4,5,6] )
Output : 3.5
The middle value of a sorted list of numbers is called
median. If the number of values is odd, it will return the
middle value. If the number is even, the median is the
midpoint of middle two values.
>>> import statistics Here ,number of values is 5, an odd
>>> a = [10,20,25,30,40] No, So returns the middle value
>>> statistics.median(a) If the number of elements is
an odd number then look
Output : 25 up else looks down.
a = [10, 20, 25,30, 40, 50]
Here ,number of values is 6, an even
>>> statistics.median(a) No, So returns the average of
Output : 27.5 middle two values.
It must be a unique items, multiple items cannot be
considered as modes. Eg. MODE of [1,2,3,2,1,2] is 2 because
‘2’ occures 3 times while MODE of [1,2,3,2,1,2,1] causes
ERROR because values 1 and 2 are repeated 3 times each.
Mode of "HIPPOPOTAMUS“ is P.
No mode for KANGAROO

Output : 2
>>> statistics.mode(“MAVELIKARA")
Output : ‘A'
import random FUNCTIONS.

When you throw a dice, it will generate a


random number between 1-6.

Have you used an OTP number? Sure it shall be a


random number. It has many uses in science, statistics,
cryptography, gaming, gambling and other fields.
If you need a 3 digit otp number, pick a
random number between 100 and 999.
The webbrowser module
is used to display web pages
through Python program. Import this module and call
webbrowser.open (URL)

import webbrowser

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/")
Give any address (URL)here.

.
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.
returns html or source code of the given url opened via
QUrl.read()
Urlopen().
Returns the http status code like 1xx,2xx ... 5xx. 2xx(200)
QUrl.getcode()
denotes success and others have their meaning.

QUrl.headers () Stores metadata about the opened url

QUrl.info () Returns some information as stored by headers.

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)
So far we have learned What are modules,
packages, and libraries? And familiarized
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

I opened another program file


and imported MYMOD (.py).
The functions written in the
module are working well.
Python does a series of actions when you import module,
They are
The code of importing modules is interprets
and executed.

Module functions and variables are available


now, but use module name as their prefix.
is a dictionary that contains the names
and definitions of defined functions and variables. Names
are like keys and definitions are values. It will avoid
ambiguity between 2 names.
I teach 2 Abhijit. one is in class XI-B and other
is in class XII-A. How can I write their name
without ambiguity.

.
class XI-B Abhijit .
class XII-A Abhijit
Example 2

The screenshot on the left


shows the module we
created.
The screenshot below shows
how to import and use that
module.

The CONVERSION.py module contains Import module


2 functions. They convert, length in feet
and inches to meters and centimeters
and vice versa
Now creating another module
named MY_MATH.py. It contains 2
functions, fact(x) and add_up_to(x).

Example 3

Import into a
new program.
Structure of a Module
DocString (Documentation String)
Functions
Constants/Variables
Classes
Objects
Other Statements
def fibi(a, b, n) :
print ("Fibonacci Series is ", end="")
for x in range(n):
print (a+b, end=", ")
a, b = b, a+b
def fibo(a, b, n) :
'''fibi () takes 3 arguments and generate Fibonacci series
„a‟ and „b‟ are previous 2 elements. N is the number of
elements we want.'''
print (" Fibonacci Series is ", end="")
for x in range(n):
print (a+b, end=", ")
a, b = b, a+b
All
Calling help of fibo function.

The documentation string is shown.

Is it interesting? Details about the


author, version and license can be
given in the 'Dockstring'.
Write this code in a
Python file and save.

Goto Python Shell and call help()


>>> import MYMOD
>>> help(MYMOD)
Calling help()
Help on module MYMOD:
NAME
Help () function gives
MYMODdocumentation about functions,
DESCRIPTION
This Module contains 4 functions. classes, modules.
1. add(a,b) -> Receives 2 Nos and return a + b.
2. sub(a,b) -> Receives 2 Nos and return a - b.
3. add(a,b) -> Receives 2 Nos and return a + b.
4. sub(a,b) -> Receives 2 Nos and return a - b.
FUNCTIONS
add(a, b)
add(a,b) in MYMOD module accepts 2 Nos and return a + b
div(a, b)
div(a,b) in MYMOD module accepts 2 Nos and return "a / b
mul(a, b)
mul(a,b) in MYMOD module accepts 2 Nos and return "a * b
sub(a, b)
sub(a,b) in MYMOD module accepts 2 Nos and return a - b
FILE
c:\users\aug 19\...\programs\python\python37-32\mymod.py
„‟‟ This module contains each function (), class, and data. „‟‟
months = ["Jan","Feb","Mar","Apr","May","Jun", \
"Jul","Aug","Sep","Oct","Nov","Dec"]
class Student :
''' Just an example of Python class'''
pass
Documentation Sting of Class.
def String_Date (d, m, y) : Function’s Documentation Sting.
''' Receives d, m, y as integers and return String Form '''
if d==1 or d==21 or d==31 :
…………
return words + months[m-1] + ", " + str(y)
Impot Module &Calling help
Name of Module

Documentation Sting of Module.

Classes defined in the Module.


Documentation Sting of Class.

Functions defined in the Module.

Documentation string of Function.


Data / Constatnts / Variable / Objects

Path of Module File


Package

Module_01.py

Module_02.py
Import modules
from them and
__init__.py use as you need.

The package is a way to organize


modules and other resources in a neat
and tidy manner.
Create Module_01.py

Create Module_02.py

Create __init__.py
Step 1.

Create Module_01.py

Create Module_02.py

Create __init__.py
Getting Current Working
Directory(folder)

Creating Folfer.
Step 2.
Create Modules. Let us try the
previous module /
import os file MYMOD.py.
os.mkdir(“MY_PACKAGE”)

Create Module_01.py

Create Module_02.py

Create __init__.py
MY >>> import os
Package >>> os.mkdir(“my_package”)

Creating MYMOD.py

Add other Modules


SAVE IN
and __init__.py files
MY_PACKAGE
>>> import os
MY
>>> os.mkdir Package

MYMOD.py
SAVE IN
MY_PACKAGE Creating
CONVERSION.py.py

Add other Modules


and __init__.py files
MY
Package

MYMOD.py

CONVESION.py
SAVE IN
MY_PACKAGE

Creating MY_MATH.py

Create __init__.py
__init__.py "Underscore underscore init
How is it underscore underscore dot py"
pronounced? Double

Underscore
”Dunder” means Double Underscore.
two leading and two trailing underscores
__init__.py file marks folders
(directories) as Python package.
This will execute automatically
when the package is imported.
The __init__.py file initialize the
Package as its name implies.
Etc..
Step 3. Create __init__.py

import os
os.mkdir(“MY_PACKAGE”)

MYMOD.py

CONVERSION.py

MY_MATH.py

Creating
__init__.py
Step 3. Create __init__.py

MYMOD.py

CONVERSION.py

MY_MATH.py

Creating
__init__.py
Step 3. Empty/Missing __init__.py
Step 3. Create __init__.py

MYMOD.py

CONVERSION.py

MY_MATH.py

Creating
__init__.py
Import into current project & use

Use later in another project.

Share with others.


Import Package
Python does a series of actions when you import package,

Python runs the initialization file __init__.py.

The modules in the package will be imported.

Defined functions of module are now available.

Creates unique namespace for each module within


the namespace of the package.
We have already learned about “ import ” statement at the
beginning of this chapter. With this statement, the module can be
imported as whole, but only the selected objects within the module
can't be imported.
The entire Math module
can be imported.


‘Pi' is an object
defined in the math module. Partial
import is not possible with the "Import"
statement.
Multiple Modules can be imported with one import
statement.

import my_package.MYMOD,my_package.MY_MATH

But it is not a
standard style.
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.
 pi (pi = 3.1415) is a constant defined in math
module. You can’t import partial components.

Only the required objects are imported. These are imported into the
local namespace so no "namespace dot" notation is required.
Output : 3.14…

Only the required objects are imported. These are imported into the
local namespace so no "namespace dot" notation is required.
It is not
possible with
“import”
Statement.

required objects are imported


Python internally does a series of actions, when we use

The code of importing modules is interprets


and executed.
Only the imported(selected) functions
and objects are available.
Does not setup a namespace for the importing
modules.
.
And use this nickname(alias) instead of real name.

Don't worry. Rename it


urllib! How I as ulib while
pronounce it. importing it.

The clause is used to


rename importing objects.
The clause is used to rename
importing objects.

python will
support unicode
malayalam.
The file name will not change, but will
get a nickname. Look at the red square.
The wild card(character) is a
letter (asterisk *) used in the
sense of “all functions and
objects”.

All objects in the math module will be


imported into the local namespace (local
scope). So there is a chance to redefine
many of the imported items.

The whole math module is imported into a


new namespace. So objects are safe and
no chance for redefining objects.
The base of natural logarithm "e" (Euler's No) is defined in
math. There is a chance to redefine its value by accident.
The "Import" statement loads a module into its
own namespace, so you must enter the module
name and dot before their components.

The "from… import" statement loads the module


components into the current namespace so you
can use it without mentioning the module name.
No crowds. The
module components
are kept in a separate
box.
Previously created package “my_package” contains
3 modules. MYMOD, MY_MATH & CONVERSION
How Import Works

Create namespace for the package and


create other 3 namespaces under it for each
modules (MYMOD, MY_MATH & CONVERSION).
Each objects goes to corresponding
module’s namespaces and were safe at
there. created Inside it and the objects of the
module were kept in them. Therefore these
namespaces should be given before the
object names.
How from … import Works

Exclude the namespace for my_package and create


namespace only for other 3 modules. Therefore statements
can be minimized when using module objects (components).

Output : 3
This initiative will make sense if you
find this presentation useful.
If you find any mistakes please
comment.

Namasthe

You might also like