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

Using Python Libraries-1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 61

USING PYTHON

LIBRARIES
COLLECTION OF
Modularizatio
n of python
program
Frame-
work

Libr- Libr-

ary1 ary2

Pack- Pack- Pack- Pack-


age1 age2 age3 age4

Framework=multiple library
mod-
ule1
mod-
ule2
Library=multiple packages
Package=multiple module
Module=multiple function/class
Using Python Libraries
Following terms must be clear while developing any python
project/program.
1. Module
2. Package
3. Library
4. Framework
1. Using Module -It is a file which contains python functions/global
variables/clases etc. It is just .py file which has python executable code /
statement.For example: Let’s create a file usermodule.py
def hello_message(user_name):
return “Hello " + name
Now we can import usermodule.py module either in python interpreter or
other py file.
import usermodule
print usermodule.hello_message(“India")
Using Python Libraries
How to import modules in Python?
Python module can be accessed in any of following way.
1.Python import statement
import math
print(“2 to the power 3 is ",
math.pow(2,3))
Just similar to math ,user
defined module can be
accessed using import
statement
2.Import with renaming
import math as mt
print(“2 to the power 3
is ", mt.pow(2,3))
3.Python from...import statement
print(“2
from math to the power
import pow3 is ", pow(2,3))
print(“2 to the power 3 is ",
Introductio
n
 As our program become larger and more complex the
need to organize our code becomes greater. We have
already learnt in Function chapter that large and
complex program should be divided into functions
that perform a specific task. As we write more and
more functions in a program, we should consider
organizing of functions by storing them in modules
 A module is simply a file that contains Python code.
When we break a program into modules, each modules
should contain functions that perform related tasks.
 Commonly used modules that contains source code for
generic needs are called Libraries.
Introductio
n
 When we speak about working with libraries in
Python, we are, in fact, working with modules that
are created inside Library or Packages. Thus a
Python program comprises three main components:
 Library or Package
 Module
 Function/Sub-routine
Relationship between Module,
Package and Library in Python
 A Module is a file containing Python definitions
(docstrings) , functions, variables, classes and
statements
 Python package is simply a directory of Python
module(s)
 Library is a collection of various packages.
Conceptually there is no difference between
package and Python library. In Python a library is
used to loosely describe a collection of core or
main modules
What is
module?
 Act of partitioning a program into individual
components(modules) is called modularity. A
module is a separate unit in itself.
 It reduces its complexity to some degree
 It creates numbers of well-defined,
documented boundaries within program.
 Its contents can be reused in other program,
without having to rewrite or recreate them.
Structure of Python
module
 A python module is simply a normal python
file(.py) and contains functions, constants and
other elements.
 Python
docstring module may
Triple contains
quoted following
comments. Useful objects:
for documentation
purpose
Variables and For storing values
constants
Classes To create blueprint of any object
Objects Object is an instance of class. It represent class in real world
Statements Instruction
Functions Group of statements
Composition/Structure of python
module
MODUL
ES
VARIAB OTHER
LES PYTHON

FUNCTION MODUL
S ES

VARIAB IMPOR
LES T
CLASS
ES
MEMBE OTHER
RS PYTHON
METHODS
MODUL
ES
Importing Python
modules
 To import entire module
 import<module name>
 Example: import math

 To import specific function/object from


module:
 from <module_name> import <function_name>
 Example: from math import sqrt

 import * : can be used to import all names


from module into current calling module
Accessing function/constant of imported
module
 To function/constant/variable of
use
module we
imported
have to specify module name and
function name separated by dot(.). This format is
known as dot notation.
 <module_name>.<function_name>
 Example: print(math.sqrt(25))
Example : import
module_name
Example: from module import
function
 By this method only particular method will be
added to our current program. We need not to
qualify name of method with name of module.
Or example:
Here function
sqrt() is
directly written

This line will


not be executed
and gives an
error
Example: from module import
*
 It is similar to importing the entire package as
“import package” but by this method qualifying
each function with module name is not required.

We can also import multiple elements of module as :


from math import sqrt, log10
Creating our own
Module
 Create new python file(.py) and type the
code as:
following Execute the following code to import
and use your own module

Save this file are


“area.py”
help()
function
 Is used to get detailed about any
information
module like : name of module, functions inside
module, variables inside module and name of file
etc.
Namespace
 Is a space that holds a bunch of names. Consider an
example:
 In a CCA competition of vidyalaya, there are students from
different classes having similar names, say there are three
POOJA GUPTA, one from class X, one from XI and one
from XII
 As long as they are in their class there is no confusion, since
in X there is only one POOJA GUPTA, and same with XI
and XII
 But problem arises when the students from X, XI, XII are
sitting together, now calling just POOJA GUPTA would
create confusion-which class‟s POOJA GUPTA. So one need
to qualify the name as class X‟s POOJA GUPTA, or XI‟s or
XII‟s and so on.
Namespace
 From the previous example, we can say that class X has its
own namespace where there no two names as POOJA
GUPTA; same holds for XI and XII.

 A namespace is a space that holds bunch of names.


 In Python terms, namespace can be thought of as a named
environment holding logical group of related objects.

 For every python module(.py), Python creates a namespace


having its name similar to that of module‟s name. That is,
namespace of module AREA is also AREA.
 When 2 namespace comes together, to resolve any kind
of object name dispute, Python asks you to qualify the
name of object as <modulename>.<objectname>
Processing of import
<module>
 The code of import module is interpreted
and executed
 Defined functions and variables in the module
are now available to program in new namespace
created by the name of module
 For example, if the imported module is area,
now you want to call the function area_circle(),
it would be called as area.area_circle()
Processing of from module import
object
 When we issue from module import object command:
 The code of imported module is interpreted and executed
 Only the asked function and variables from module are now available in
the current namespace i.e. no new namespace is created that’s why we
can call object of imported module without qualifying the module
name
 For example:
from math import sqrt
print(sqrt(25))
 However if the same function name is available in current
namespace then local function will hide the imported module’s
function
 Same will be apply for from math import * method
Using Python‟s Built-in
Function
 Python‟s standard library is very extensive that
offers many built-in functions that we can use
without having to import any library.
 Using Python‟s Built-in functions
 Function_name()
Mathematical and String
functions
 oct(int) : return octal string for given number by prefixing
“0o”
 hex(int) : return octal string for given number by prefixing
“0x”
Mathematical and String
functions
 int(number) : function convert the fractional
number to integer
 int(string) : convert the given string to integer
 round(number,[nDIGIT]) : return number rounded
to nDIGIT after decimal points. If nDIGIT is not
given, it returns nearest integer to its input.
 Examples: (next slide)
Mathematical and String
functions
Other String
function
 We have already used many string function in class
XI, here are few new functions
 <string>.join() : if the string based iterator is a string then
the <string> is inserted after every character of the string.
 If the string based iterator is a list or tuple of strings then, the
given string/character is joined after each member of the list of
tuple. BUT the tuple or list must have all members as string
otherwise Python will raise an error
 Examples (next slide)
Other String
function
Other String
function
 We have already used many string function in class
XI, here are few new functions
 <string>.split() : allow to divide string in multiple parts
and store it as a LIST. If you do not provide delimeter then
by default string will be split using space otherwise using
given character.

 <str>.replace() : allows you to replace any part of string


with another string.

 Example (NEXT SLIDE)


Example (split() and
replace())
Creating a Python Library
Package –
 collection of python modules under a common

namespace.
 Have different modules on a single directory with

some special files(such as __init__.py (content is


empty))
 If you don’t have __init__.py inside then it is called as

folder and not as package.


Structure of a package
Package:
Package vs Folder
Creating Package
 Step 1
 Create a new folder which you want to act as package. The
name of folder will be the name of your package

IN THE C:\USERS\VIN
A new Folder “mypackage”
is created.
Note: you can create folder
in
any desired location
Creating Package
 Step 2: Create modules (.py) and save it in
“mypackage” folder numcheck.py

area.py
Creating Package
 Step 2: importing package and modules in python
program

Save this file by


“anyname.py”
outside the package
folder

RUN THE
PROGRAM
Creating Alias of Package/module
 Alias is the another name for imported package/module.
It can be used to shorten the package/module name

Save this file by


“anyname.py”
outside the package
folder

RUN THE
PROGRAM
Types of Modules
 There are various in-built module in python, we
will discuss few of them
 Math module
 Random module
 Statistical module
Math
module
 This module provides various function to
perform arithmetic operations.
 Example of functions in math modules are:
sqrt ceil floor pow
fabs sin cos tan
 Example of variables in math modules
are:
 pi
 e
Math module
functions
 sqrt(x) : this function returns the square root
number(x)
of module name is
required before
. function name
here
 pow(x,y) : this function returns the
(x)y module name is not
required before
function name here

 ceil : this function return the x rounded to next


(x)
integer.
Math module
functions
 floor(x) : this function returns the x rounded to
previous integer.
 fabs(x) : this function returns absolute value of
float x. absolute value means number without any
sign

 sin (x) : it return sine of x (measured in


radian)
Math module
functions
 cos(x) : it return cosine of x (measured in
radian)

 tan(x) : it return tangent of x (measured in


radian)

 pi : return the constant value of pi (22/7)

 e : return the constant value of constant e


Using Random
Module
 Python has a module namely random that provides
random – number generators. Random number
means any number generated within the given
range.
 To generate random number in Python we have to
import random module
 2 most common method to generate random number
in python are :
 random() function
 randint(a,b) function
random()
function
 It is floating point random number generator
between 0.0 to 1.0. here lower limit is inclusive
where as upper limit is less than 1.0.
 0<=N<1
 Examples:

Output is less than 1


random()
function
 To generate random number between given range
of values using random(), the following format
should be used:
 Lower_range + random() * (upper_range-
lower_range)
 For example to generate number between 10 to 50:
 10 + random() * (40)
randint()
function
 Another way to generate random
number is randint() function, but it generate
integer numbers.
 Both the given range values are inclusive i.e. if we
generate random number as :
 randint(20,70)
 In above example random number between 20 to 70
will be taken. (including 20 and 70 also)
E

P
L
E
O

T
P

T
Just a
Minute…
 Give the following python code, which is repeated
four times. What could be the possible set of
output(s) out of four sets (ddd is any combination
of digits)
import random
print(15 + random.random()*5)
a) b) c) d)
17.ddd 15.ddd 14.ddd 15.ddd
19.ddd 17.ddd 16.ddd 15.ddd
20.ddd 19.ddd 18.ddd 15.ddd
15.ddd 18.ddd 20.ddd 15.ddd
Just a
Minute…
 What could be the minimum possible and
maximum possible numbers by following code
import random
print(random.randint(3,10)-
3)
 In a school fest, three randomly chosen students out
of 100 students (having roll number 1 -100) have
to present the bouquet to the guests. Help the
school authorities choose three students randomly
Just a
Minute…
Just a
Minute…
Look at the following Python code and find the possible output(s) from the
options (i) to (iv) following it. Also, write the maximum and the minimum values
that can be assigned to the variable PICKER.
Note:
‐ Assume all the required header files are already being included in the code.
‐The function randint() generates an integer between 1 to n
import random
PICKER=1+random.randint(0,2)
COLOR=[”BLUE”,”PINK”,”GREEN”,”RED”]
for I in range(1,PICKER+1):
for j in range(I+1):
print(COLOR[j],end=‘’)
print()
What are the possible outcome(s)
executed from the following code?
Also specify the maximum and
minimum values that can be
assigned to1)DELHIDELHI
variable PICK
2)
DELHI
MUMBAIMUMBAI DELHIMUMBAI
CHENNAICHENNAI DELHIMUMBAICHENN
AI
KOLKATAKOLKAT
A
3) 4)
DELHI DELHI
MUMBAI DELHIMUMBAI
CHENNAI KOLKATAKOLKATAKOLKATA
KOKLATA
randrange()
function
 This function is also used to generate
random number within given range.
 Syntax
 randrange(start,stop,step)
It will generate random
number between 5 to
14

random output between 5 to 14, may vary


randrange()
function
It will generate
random number
between 1 to 29 with
stepping of 2 i.e. it
will generate number
with gap of 2 i.e.
1,3,5,7 and so on
Mathematics Game for
Kids
Mathematics Game for
Kids
Statistical
Module
 This module provides functions forcalculating
mathematica statistics of numeric (Real-valued)
l data.
 We will deal with 3 basic function under this
module
 Mean
 Median
 mode
Mea
n
 The mean is the average of all numbers and is
sometimes called the arithmetic mean.

55, is the average of all numbers in the list


Media
n
 The median is the middle number in a group
of numbers.
With odd number of
elements it will simply
return the middle
position value

With even number of


elements, it will return
the average of value
at mid + mid-1 i.e.
(50+60)/2 = 55.0
Mod
e
 The mode is the number that occurs most often
within a set of numbers i.e. most common data in
list.

Here, 10 occurs
most in the list.

You might also like