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

Using Python Libraries

Class 12 Computer Science, Chapter 4 - Using Python Libraries. Self learning Presentation in the form of Teacher - Student conversation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Using Python Libraries

Class 12 Computer Science, Chapter 4 - Using Python Libraries. Self learning Presentation in the form of Teacher - Student conversation.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 101

Write programs.

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

Sharing (Reuse) of Code


Modular Programming
The process of dividing a complex program into smaller
parts or components is called modular programming.
s k . Modules
ta ?
b i g do
s a n I
It ' c a
w t u s
Ho Le t .
it i Can
spl join you
tog
eth
r? e
After
completion join
it together.
Friends,
Modules Module 1 assigning to Aswin
Module 3 and 5 goes to Naveen
Module 4 to Abhishek, 2 to
Sneha
and .., Abhijith will lead you.

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 ?

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 fi le and save it with a
name with .py suffi x.
It becomes a module.

Any Python file can be referenced as a module.


Can you try your Yes 2 . I want to write
own modules ? some more module
fi les.

Good. That is Package.

Collection of modules
are called package.
What 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.
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.

Packages are like folders, modules are


like files in that folder. The library is a
collection of one or more packages.
Some commonly used libraries.
PYTHON has rich libraries.
Some are ready for use , others
need to be installed.
Some commonly used libraries
1. Standard library
2. Numpy library
3. Scipy library
4. Tkinter library
5. Matplotlib library
Brief study in the standard library.
Standard Library is a ready for use Library.
The Python Standard Library contains
built-in data, functions, and many
modules. All are part of the Python
installation.Basic Contents of Standard Library.

1. Built-Data and Functions


2. Math module
3. Cmath module
4. Random module
5. Statistics module
6. Urllib module
Built-in and importing
Look at the board.
components. Some are ready to use and
others need to be imported
Built-in
Data, 1 The components in the
functions 'Built-in' category are basic,
+ more so they are ready for use
2 Parts of Standard Library
Module to import
2
1. Math module These must be
2. Cmath module
3. Random module imported
4. Statistics module before use.
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 import


Statement to
import other modules into our
programs.
Examples of Built-in Function.
Accept an integer in any system and returns
hex ( Integer Argument )
>>> hex ( 10 ) its Hexadecimal equivalent as string.
OUTPUT : ‘0xa’ Can you count 1 to
oct ( Integer Argument
Accept)an integer in any
20 in octal and hexa-
>>> oct ( 10 ) system and returns its octal decimal systems?
OUTPUT : ‘0o12’ equivalent as string.
In oct, 1, 2, 3, 4,
5, 6, 7, What
int ( string / float Argument )

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.

print ("Numbering System Table")


print("column 1: Decimal System, col2 : Octal, col3: Hex, col4: Binary")
for a in range(1,25): Binary of
given num CODE
print(a, oct(a), hex(a), bin(a) ) ber.
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.
Do it in Python. 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) I have
OUTPUT : 3 no exa
you ha ct bala
>>> int( “123” ) ve 65 p n ce. D
OUTPUT : 123 Other a i s e.? o
w ise You
Rs 3.6 r
round (float , No of Decimals) 5 is ro bill amou
unded nt
>>> round ( 3.65 , 0 ) to Rs 4
OUTPUT : 4.0
.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.
String Functions. Can y
o
"Anil u split
Join the words “lion”, “tiger” and Kuma
“leopard” together. r"?
Replace all "a" in “Mavelikkara” with "A".
He w No
ill cru
sh m
Split the line 'India is my motherland' e.
into separate words.

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


“anil” * 3 = “anilanilanil”. These are
the basic operations of a string.
Functions like Join(), replace(),
split() are also there. They do the
same actions as the name implies.
string.split() function splits a string into a list.
String functions are little tricky. They are invoked
with string variable as prefix. String.function()
I want to split each words fr om the
line "All knowledge is within us.”
Try it in Python
>>> x = "All knowledge is within us.“
%

Prefix
.
>>> x split()
We get the list ['All', 'knowledge', 'is', 'within', 'us.']
split(x)
 Wrong use x.split()
 Right use

split(“All knowledge is within us.”) “All knowledge is within us.”.split()


You can tell where to split.
Cut the names when you see ",“.
“Mathe w,Krishna,David,Ram”
>>> x = "Mathew,Krishna,David,Ram" Do it in Pyt
hon
>>> 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.
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 ‘ , '.

Delimit string.join ( collection of string )


Take each item
from collection “,”. join ( [‘Item1’, ‘Item2’,
and place ‘Item3’] ) 1
‘Item1’ 2
delimiter symbol ‘Item1,Item2’ 3 d watch
lo ad an tion.
between
Enditems. Item1,Item2,Item3 Down t anima
to ge

>>> a = ['Matthew', 'Krishna', 'David','Ram']


>>> ",".join(a) OUTPUT : 'Matthew,Krishna,David,Ram'
A list [ ‘Thrissur’, ‘Ernakulam’, ‘Kottayam’,
‘Mavelikkara’ ] includes the major stations
between Shoranur and J o Mavelikkara.
i s ? in t
k
th
e Plac he list
i
r i n g l
> betw e the d with ‘ -
s t - e e n elim > ’.
a ulam ’ corr i
m
e
ak n ak ka ra ect list ele ter ‘->’
o u E r i k ? men in
n y - > v e l ts. I
a
C riss -> Mu r a s it
‘Th ayam
K o tt
Do it in Python.
>>> a = ['Trissur','Ernakulam','Kottayam', 'Mavelikara' ]
>>>> "->".join(a)
'Trissur->Ernakulam->Kottayam->Mavelikara'
replace () Function. replace () Function. function
Can you change replaces a phrase with another
zebra to cobra? phrase.
Eas string.replace(what, with, count )
‘ze’ y…
wit repla What to replace?
h ‘c ce
o’ Replace with what?
How many replacement is
needed.(optional)
Do it in Python
>>> ‘zebra’.replace(‘ze’,’co’)
cobra zebra becomes cobra

>>> ‘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.

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
Actions behind imoprting modules.
Python does a series of actions when you import module,
They are
The code of importing modules is interpreted
and executed.

Defined functions and variables in the


module are now available.

A new namespace is setup for importing modules.


module name act as NameSpace
NameSpace
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.
Use like this
.
class XI-B Abhijit .
class XII-A Abhijit
NameSpace
When using an item of a module, the module
name(NameSpace) must be placed as prefix.
Namespace is a dictio nar y o f var iable
names (keys ) an d their co rr es po n din g
Are not Ashwin in 12.B? valu es (o bjects ).
Your Reg. No 675323. Dict_12_A = {“Abhishek”:675321, …,
…}
No Sir, Check
List of 12.A (Namespace) List of 12.B (Namespace)
the list of 12.A
Name(Key) : Value Name(Key) : Value
Abhishek : 675321 Indrajith : 675320
Ashwin : 675322 Ashwin : 675323
Sneha : 675323 Niranjan : 675325
Naveen : 675324 Adithya : 675326

e na m e s pace. r n a m e spa ce.


This is on Anot he

Name - value pair is


called Dictionary.
Use and usage of namespace.
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 sqrt(25)
Output : 5
>>> math.pi
Output :3.141592653589793
Importi ng math Modules.
math and cmath modules covers many mathematical
functions. The Math module is used for general numbers
and the cmath module is used for complex numbers.
More than 45 functions and 5 constants are defined in it.
The use of these functions can be understood by their
name itself.
Remember 2 things before using functions of math module.
1. import math

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


>>> locals() math module imported into local scope.
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module
'builtins' (built-in)>, 'math': <module 'math' (built-in)>}
>>>

A new namespace is setup for


importing modules.
Importi ng math module.
>>> help(math)

Traceback (most recent call last): File "<pyshell#1>", line 1, in <module>
help(math)
NameError: name 'math' is not defined


>>> 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.

Import module, before using math,


cmath, random, webbroser, urllib
modules.
import math
abs ( No ) and fabs ( No )
.
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

factorial ( +ve int argument ) 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)

>>> 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.

What is the remainder when


10.32 is divided by 3? >>> import math
 = 3 >>> math.fmod(10.32,3)
1.32
What is the remainder when
11.5 is divided by 2.5? >>> import math

  = 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.

>>> 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
statistics.median(list of Nos)
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 middle
Output : 27.5 two values.
statistics.mode(list of Nos)
Mode is the most occurring item in a list of items.
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.
>>> import statistics No mode for KANGAROO
>>> a = [1,2,3,2,1,2]
>>> statistics.mode(a)
Output : 2
>>> statistics.mode(“MAVELIKARA")
Output : ‘A'
import random .
random FUNCTIONS.
A random number is a number chosen as if by chance. Guess a
number between 1 and 100. It may be 5 or 23 or 91. You guess it by
chance. Such numbers are called random numbers. Random
module implements pseudo-random number generators that help

.
you to make random numbers. Don't forget to import random module
and use the function with randomprefix.

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.
Returns a random float number between
random.random ()
0 and 1. It has no argument.
>>> import random b er
nu m
>>> random.random() a r an d o m
0 0
u wa n t it b y 1
Output : 0.6024570823770099 If yo l ti p ly
1 0 0 , mu r.
e l ow te ge
>>> int(random.random()*100) b
k e th e i n
and ta
Output : 60

random.randint (Start, End) Returns a random number in


>>> import random between given range including
>>> random.randint(1,100) start and end. Both arguments are
Output : 79 int type.
>>> random.randint(100,999) If you need a 3 digit otp number, pick a
Output : 627 random number between 100 and 999.
random.choices
Choice()() function randomly selects an item from a
sequence. The sequence may be a string, range, list, tuple or any
other kind of sequence. e r fro m
e ct a l ett
Sel n am e .
>>> import random your
>>> random.choices(“VIDYADHIRAJA”)
Output : R

random. sample (sequence, No of items)


Returns certain items randomly from a sequence. The output will
be a list. Select any 3 persons
>>> import random fr om the list.
>>> a = [“anil”, “babu”, “Hari”, “rajan”, “jacob”, “Mathew”]
>>> random.sample(a,3)
Output : ['babu', 'jacob', 'Hari']
The webbrowser module import webbrowser.
is used to display web pages
through Python program. Import this module and call
webbrowser.open(URL)
o u r Fa c eb o o k
Open y
import webbrowser 2 lin e c o d es .
with

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.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)
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

How to create our


own modules.
Making our own modules
Wr i te t h e
code on th
i n a fi l e a n e b oa rd
d save it w
name with i t h a
. p y s u ffi x .
It becomes
a module.

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.

Import this module in


another program and use
the functions of it, as you
like.
But remember one thing. Always use the module
name as the prefix of the function.
Example
Importing module
Using Module Fine, but the
Na m e a s p re fi x computer does a lot
of things when you
import a module,
without knowing
you.

I opened another program file


and imported MYMOD (.py). The
functions written in the module
are working well.
Actions behind importing modules.
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.

A new namespace is setup for importing modules.


module name act as NameSpace
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.
Use like bellow
.
class XI-B Abhijit .
class XII-A Abhijit
NameSpace
When using an item of a module, the module
name(NameSpace) must be placed as prefix.
Local Scope before and after imoprting MYMOD.py

Local Scope before importing MYMOD.py.

Local Scope after importing MYMOD.py.

A new Namespace is created when you import MYMOD.


.
Use “MYMOD “ as prefix when you use its components.
Example 2

The screenshot on the left


shows the module we
1 feet = 30 cm created.
1 inch = 2.5 cm The screenshot below shows
how to import and use that
module.

The CONVERSION.py module Import module


contains 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
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

None of them are mandatory.


Docstring/Documentation String
def fibi(a, b, n) :
Sure, Docstring will
help you
print ("Fibonacci Series is ", end="") .
d e r s t a n d
n g u n a t?
for x in range(n): N o t h i
s r e p r e se n t s w h
t
A r g u m e n f u n c t i o n' d o ?
print (a+b, end=", ") W h a t d o e s '
l r e t u r n ?
t wi l
a, b = b, a+b W h a

Docstring or Documentation string


is a string that provides a
Documentation or help topic. (what the
function do).
Docstring documentation string, should be placed at
the beginning of function(). Use single / double / triple
quotes to enter the documentation string. Triple quotes
are better, because it can be extended to multiple lines.

def fibo(a, b, n) : Docstring/Documentation


'''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="")
All doubts will be gone
for x in range(n):
away when the
print (a+b, end=", ") documentation string
a, b = b, a+b is given.
All
When you call help, Docstring (documentation string)
will appear. Documentation string can be given to
functions, classes and modules.

Calling help of fi bo function.

The documentation string is shown.

Is it interesting? Details about the


author, version and license can be
given in the 'Dockstring'.
How to Give docstring

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, Come to
DESCRIPTION Python Shell.
This Module contains 4 functions. classes, modules.
1. add(a,b) -> Receives 2 Nos and return a + b. Import
2. sub(a,b) -> Receives 2 Nos and return a - b. MYMOD and
3. add(a,b) -> Receives 2 Nos and return a + b.
4. sub(a,b) -> Receives 2 Nos and return a - b. call
FUNCTIONS
add(a, b)
help(MYMOD)
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
Structure of a module.
‘’’ This module contains each function (), class, and data. ‘’’
months = ["Jan","Feb","Mar","Apr","May","Jun", \
Docstring
"Jul","Aug","Sep","Oct","Nov","Dec"] Variables,
class Student : Constants,
Classes Definitions Objects
''' Just an example of Python class'''
Documentation Sting of Class.
pass
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 : Function Definitions
…………
return words + months[m-1] + ", " + str(y)
Impot Module &Calling help
Name of Module

Documentation Sting of Module.

Classes defi ned in the Module.


Documentation Sting of Class.

Functions defi ned in the Module.

Documentation string of Function.


Data / Constatnts / Variable / Objects

Path of Module File


When you get some
Making our own Packages songs, should you
How many modules we copied all in desktop?
created so far? e a
l l cre at
o, I w i th em .
s N d c o p y
od u l e d e r a n
Fou r M fo l
Absolutely right. Package as Folders
like that, Real programs
are large in size. They
contain many modules.

We sort these and


store them in different
folders.
Packages are like folders and modules are like files in that folder.
Package as Folders
Package Packages are folders that contain related module
and other sub-packages.
Module_01.py
The 'package' may contain
Module_02.py other sub-packages in it.
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.
Steps for Making Packages

Packages are folders and


Modules are files in them.

1 Create a folder or directory


Inside that folder, create or
2 move some Module (.py Files)
Create a file named __init__.py in
3 this folder. (It may be Empty)
Three Steps for Making Packages
Collection of modules(.py Files) saved in a folder are
called package. Package and folder names must be the
r
same. Packages are like folders and modules
f olde
ate ge
Cr e
P a c ka 1 Create folder are like files in that folder.

Create Module_01.py
Create Module (.py Files)
2 inside the folder
Create Module_02.py

Create __init__.py Create __init__.py inside


3 this folder.
Step 1. Create Folder
Create a folder with the name of the
o l der
a te f package you are going to create, in
Cre ckage
Pa
1
Python Instalation folder.
d o t h i s i n
Create Module_01.py Yo u c a n e
o w s F i l
Wi nd in Pytho n
g e r O r e .
Mana O S M o d u l
Create Module_02.py usi n g

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

CONVERSION contains 2 functions to_feet(m,cm) & to_meter(f,i)


MYMOD contains 4 functions add(x,y),sub(x,y), mul(x,y) & div(x,y)
MY_MATH contains 2 functions add_up_tyo(x), fact(x)
Step 1. Create Folder
t e OS module provides file management functions
1 r ea ge
C cka
such as getcwd () and mkdir ()
_pa
my
Step 1 getcwd() -> Get Current Working Directory.
Create a folder mkdir() Make directory (Create folder)
named
my_package
Gett ing Current Working
Directory(folder)

Creating Folfer.
Create folder anywhere using any method. But
Step 2. must be added to the System path

Create Modules. Let us try the


previous module /
1 Done
_ P ac kage import os fi le MYMOD.py.
M Y
e r c r ea ted
fold
os.mkdir(“MY_PACKAGE”)

Create Module_01.py Step 2


Create one or more
Create Module_02.py
modules in this folder. Or
copy/move existing files
Create __init__.py into this folder.
Step 2 Create Module. Creating MYMOD.py
Module described in slide No 49. It contains 4
functions add(x,y) , sub(x,y), mul(x,y) & div(x,y,)
MY >>> import os
Package
>>> os.mkdir(“my_package”)

Creating MYMOD.py

Add other Modules


SAVE IN and __init__.py files
MY_PACKAGE
Step 2 Create Module. Creating
CONVERSION.py Module described in slide No
54. It contains
2 functions, to_meter(f, i) , to_feet(m, cm)

>>> import os
MY
>>> os.mkdir Package
1 feet = 30 cm
inch = 2.5 cm MYMOD.py
SAVE IN
MY_PACKAGE Creating
CONVERSION.py.py

Add other Modules


and __init__.py files
Step 2 Create Module. MY_MATH
Module described in slide No 55. It
contains 2 functions fact(x) ,
add_up_to(x)
MY
Package x a nd
u p t o
Count i t h f
MYMOD.py mul t i p l y w

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

__init__.py "Underscore underscore init


How is it underscore underscore dot py"
pronounced? Double
Dunder init dunder.py
Underscore
”Dunder” means Double Underscore.
two leading and two trailing underscores
__Init__.py is a Dunder or magic file
that creates packages from a folder.

Without this, everything else will be wasted.


Impotance of __init__,py file

1 __init__.py file marks folders


(directories) as Python package.

2 This will execute automatically


when the package is imported.

3 The __init__.py file initialize the


Package as its name implies.
Etc..
Step 3. Create __init__.py
1 All Not all folders are
_ Pa ck age Done
MY
a t ed import os packages. But all
e
folder cr os.mkdir(“MY_PACKAGE”)
packages are folders.
MYMOD.py
2
CONVERSION.py Step 3
MY_MATH.py
Folders become a
Creating 3 package when they have
__init__.py __init__.py file.
Step 3. Create __init__.py
1
_ P ac k age All Step 3
MY
c r eated
fold er
Done If the __init__.py file is empty, we
MYMOD.py
can import the package but
can‘t use it. Because
CONVERSION.py initialization has not been
2
MY_MATH.py done. init refers to
‘initialization’. When the
Creating 3 Package being imported,
__init__.py __init__.py automatically execute
and initialize the Package.
Step 3. Empty/Missing __init__.py

If the __init__.py file is empty or missing,


we can import the package but can‘t use
No __init__.py In Content
it. Because initialization did not
Section
happened.
The package cannot be used.
Step 3. Create __init__.py
1
MY _ P ac k age Do
ne So, write following code in
ld er c r eated
fo
__init__.py
MYMOD.py
import my_package.MYMOD
CONVERSION.py
import my_package.CONVERSION
2
MY_MATH.py
import my_package.MY_MATH

Creating Save the file in


__init__.py Step 3 my_package
What after creating a package ?
t e
o c o m
u 3 st
l
p ?e
e p s What next?
id y l l
D a
Import into current project & use
t in g
rea Use later in another project.
, C y
Yes lder, nit__.p
Fo nd __i
es a Share with others.
d u l
Mo
Packages are the basic
unit for code sharing.
What next? Import Package
Import Package There are 3
modules in this
package.
Uses functions in modules
CONVERSION,
MYMOD and
MY_MATH. See
how them used.
What happens when we import packages.

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.
Different Forms of import
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
import math
 can be imported.

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.

from math import pi 


from math import pi, sqrt, pow, fmod 
Only the required objects are imported. These are imported into the
local namespace so no "namespace dot" notation is required.
>>> pi  Output : 3.14… >>> math.pi

import selected objects
from math import pi, sqrt, pow, fmod
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


Actions behind from … imoprt.
Python internally does a series of actions, when we use
from <module> import <object>
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.
module name act as NameSpace
Renaming modules.
A module (object) can be renamed when it is imported. 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 'as' clause is used to


rename importing objects.
import <module> as <New Name>
from <module> import <object> as <New Name>
Renaming modules.
The 'as' clause is used to rename
importing objects.
import <module1> as <New Name> , <module2> as <New Name>
from <module> import <object> as <New Name>,<object2> as <New Name>
python will
import urllib as ulib support unicode
malayalam.
import statistics as stat
import math as കണക്ക്
from math import factorial as fact
Renaming modules.

Importing Modules
with new NAME

Using function with


NICKNAME(alias)

The file name will not change, but will


get a nickname. Look at the red square.
Wild character/wildcard
importing.
al l
o r t The wild card(character) is a
im p ath
yo u m m e? letter (asterisk *) used in the
a n fro du l
C jects mo sense of “all functions and
o b
th e impo
objects”.
math rt from math import *
is i t ?
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.
import math
The whole math module is imported into a
new namespace. So objects are safe and
no chance for redefining objects.
Chance to redefine imported objects
The base of natural logarithm "e" (Euler's No) is defined in
math. There is a chance to redefine its value by accident.
i f y ou
p e n s
t h a p
Wha e = 123?
e fi n e
d

It will change the existing value.


Import vs from … import
The "Import" statement loads a module into its
own namespace, so you must enter the module
name and dot before their components.
>>> import math 
>>> math.sqrt(25)
The "from… import" statement loads the module
components into the current namespace so you
can use it without mentioning the module name.
>>> from math import sqrt
>>> sqrt(25) 
import vs from … import
"Import" statement loads
Import the whole
Module. the whole module into a
new (own) namespace.
It is not possible to import
selected components.
New namespace created.
t n o t a t i o n n eeded Import sqrt()
Do
function only.
“from .. import"
statement loads whole
or selected components
Loaded to current
into current namespace No “DOT” notation. namespace
Drawback of from ... import *
No crowds. The
module components
All are in separate namespace are kept in a separate
box.

All in local scope. Heap of objects Oh. My God!,


All in local scope.
Heap of objects!!!
Everyone is worthy in their own place.
Previously created package “my_package” contains
3 modules. MYMOD, MY_MATH & CONVERSION
Don't think "from...import" How Import Works
is good for nothing. import my_package
Everyone is worthy Create namespace for the package and
in their own place. 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.
Everyone is worthy in their own place.
How from … import Works
from my_package import *
Exclude the namespace for my_package and create
namespace only for other 3 modules. Therefore statements
can be minimized when using module objects (components).

Use MYMOD.add (x,y) instead of my_package.MYMOD.add (10,20)

from statistics import mean as average


>>> average( [1,2,3,4,5] ) Output : 3
Despite the many drawbacks, the advantage of "from ..
import" is that we can only import the items we need
Type online in Malayalam and cut and paste.

Write the program. Enjoy programming.


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

Namasthe

You might also like