Using Python Libraries. - PowerPoint PPT Presentation

About This Presentation
Title:

Using Python Libraries.

Description:

Class 12 Computer Science, Chapter 4 - Using Python Libraries. Self learning Presentation in the form of Teacher - Student conversation. – PowerPoint PPT presentation

Number of Views:2781

less

Transcript and Presenter's Notes

Title: Using Python Libraries.


1
Write programs. Enjoy programming.
SELF LEARNING PRESENTATION. .pptx Format
Programming is an amazing experience.
CHAPTER 4
USING PYTHON LIBRARIES
All images used in this presentation are from the
public domain
2
Modular Programing Sharing (Reuse) of Code
3
Modular Programming
The process of dividing a complex program into
smaller parts or components is called modular
programming.
Modules
It's a big task. How can I do ?
Let us split it.
Can you join together?
After completion join it together.
4
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.
Modules
One part of a complex task is called module.
5
Code reuse
def fact(x1) f 1 for n in range(2,x1) f
- n return f def add(a,b) return ab def
fibo(a-1,b1,n10) if n0
return print(ab) fibo(b,ab,n-1) Pi 3.14
The use of existing code or modules in further
development is called 'code reuse'
I need this code again in another program.
6
Modules, packages, and libraries are all
different ways to reuse a code.
Modules Packages libraries
7
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.
8
Write the code on the board in a file and save it
with a name with .py suffix. It becomes a
module.
Any Python file can be referenced as a module.
9
Can you try your own modules ?
Yes2. I want to write some more module files.
Good. That is Package.
Collection of modules are called package.
10
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.
11
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.
12
Some commonly used libraries.
PYTHON has rich libraries. Some are ready for
use, others need to be installed.
  • Some commonly used libraries
  • Standard library
  • Numpy library
  • Scipy library
  • Tkinter library
  • Matplotlib library

13
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.
  • Built-Data and Functions
  • Math module
  • Cmath module
  • Random module
  • Statistics module
  • Urllib module

14
Look at the board. Some are ready to use and
others need to be imported
  • Built-in
  • Data,
  • functions
  • more
  • Module to import
  • Math module
  • Cmath module
  • Random module
  • Statistics module
  • Urllib module

The components in the 'Built-in' category are
basic, so they are ready for use
1
2 Parts of Standard Library
2
These must be imported before use.
15
print ( "10 20 ", 10 20 ) print ( "Cube of
2 is ", 2 3 ) import math print ("Square root
of 25 is ", math.sqrt(25) ) print ("Cube of 2 is
", math.pow(2,3) )
print(), input(), 10 20 are basic operation.
No need to import anything.
sqrt () and pow () are defined in Math module. So
need to import math modules.
import
We use the Statement to import other modules
into our programs.
16
Examples of Built-in Function.
hex ( Integer Argument ) oct ( Integer
Argument ) int ( string / float Argument
) round ( )
Accept an integer in any system and returns its
Hexadecimal equivalent as string.
gtgtgt hex ( 10 ) OUTPUT 0xa
Can you count 1 to 20 in octal and hexa-decimal
systems?
Accept an integer in any system and returns its
octal equivalent as string.
gtgtgt oct ( 10 ) OUTPUT 0o12
In oct, 1, 2, 3, 4, 5, 6, 7, What next ?
The int() function returns integer value of given
value.
gtgtgt int ( 3.14 ) OUTPUT 3
In hex, 1, 2, 3, 4, 5, 6, 7, 8, 9, What next ?
The given float number is rounded to specified
number of decimal places.
gtgtgt round ( 3.65,0 ) OUTPUT 4.0
17
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.
In hex, 1, 2, 3, 4, 5, 6, 7, 8, 9, What next ?
In oct, 1, 2, 3, 4, 5, 6, 7, What next ?
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.
18
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) print(a,
oct(a), hex(a), bin(a) )
Binary of given number.
CODE
Numbering System Table column 1 Decimal System,
col2 Octal, col3 Hex, col4 Binary 1 0o1 0x1
0b1 2 0o2 0x2 0b10 3 0o3 0x3 0b11 4 0o4
0x4 0b100 5 0o5 0x5 0b101 6 0o6 0x6 0b110
16 0o20 0x10 0b10000 17 0o21 0x11
0b10001 18 0o22 0x12 0b10010 19 0o23 0x13
0b10011 20 0o24 0x14 0b10100 21 0o25 0x15
0b10101 22 0o26 0x16 0b10110 23 0o27 0x17
0b10111 24 0o30 0x18 0b11000
OUTPUT
oct() convert given value to octal system. hex()
convert given value to Hexadecimal system. bin()
convert given value to Binary system.
19
int () and round () Function.
Do it in Python.
int ( float/string Argument ) round (float
, No of Decimals)
The int() function returns integer value (No
decimal places) of given value. The given value
may be an integer, float or a string like 123
gtgtgt int ( 3.14 ) OUTPUT 3 gtgtgt int
(10/3) OUTPUT 3 gtgtgt int( 123 ) OUTPUT 123
I have no exact balance. Do you have 65 paise.?
Otherwise Your bill amount Rs 3.65 is rounded to
Rs 4.0
gtgtgt 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 ( gt.5) then the digit before it will
be added by 1.
20
Can you split "Anil Kumar"?
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. Functions like
Join(), replace(), split() are also there. They
do the same actions as the name implies.
No He will crush me.
21
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 from the line "All
knowledge is within us.
Try it in Python
gtgtgt x "All knowledge is within us. gtgtgt We
get the list 'All', 'knowledge', 'is', 'within',
'us.'

x.split()
Prefix
?
?
split(x) split(All knowledge is within us.)
x.split() All knowledge is within us..split()
Wrong use
Right use
22
You can tell where to split.
Cut the names when you see ",. Mathew,Krishna,Da
vid,Ram
gtgtgt x "Mathew,Krishna,David,Ram" gtgtgt x.split(
, ) We get the list 'Mathew', 'Krishna',
'David', 'Ram'
Do it in Python
gtgtgt x "Mathew\nKrishna\nDavid\nRam" gtgtgt
x.split( \n ) We get the list 'Mathew',
'Krishna', 'David', 'Ram'
Cut when you see \n.
gtgtgt x "MAVELIKARA" gtgtgt x.split("A") We get the
list 'M', 'VELIK', 'R', ''
"MAVELIKARA"
Is it Fun?

23
string.join() joins a set of string into a single
string.
Join the list 'Matthew', 'Krishna',
'David','Ram' into a single string like
'Matthew, Krishna, David, Ram'. Names should be
joined by the glue ,'.
Delimit string.join ( collection of string )
Take each item from collection and place
delimiter symbol between items.
1
2
Download and watch to get animation.
3
Item1,Item2,Item3
End
gtgtgt a 'Matthew', 'Krishna', 'David','Ram' gtgtgt
",".join(a)
OUTPUT 'Matthew,Krishna,David,Ram'
24
A list Thrissur, Ernakulam, Kottayam,
Mavelikkara includes the major stations
between Shoranur and Mavelikkara.
Join the list with -gt. Place the delimiter
-gt in between list elements. Is it correct ?
Can you make a string like this? Thrissur-gt
Ernakulam -gt Kottayam-gt Mavelikkara
Do it in Python. gtgtgt a 'Trissur','Ernakulam','K
ottayam', 'Mavelikara' gtgtgtgt "-gt".join(a) 'Trissu
r-gtErnakulam-gtKottayam-gtMavelikara'
25
replace () Function.
replace () Function. function replaces a phrase
with another phrase.
Can you change zebra to cobra?
string.replace(what, with, count )
Easy replace ze with co
What to replace? Replace with what? How many
replacement is needed.(optional)
Do it in Python
gtgtgt zebra.replace(ze,co) cobra zebra
becomes cobra gtgtgt cobra.replace(co,ze) zebr
a cobra becomes zebra
26
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 lt module Name
gt E.g. import math import random
27
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
28
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.
29
Namespace is a dictionary of variable names
(keys) and their corresponding values (objects).
Are not Ashwin in 12.B? Your Reg. No 675323.
Dict_12_A Abhishek675321, ,
No Sir, Check the list of 12.A
List of 12.A (Namespace) Name(Key)
Value Abhishek 675321 Ashwin
675322 Sneha 675323 Naveen
675324
List of 12.B (Namespace) Name(Key)
Value Indrajith 675320 Ashwin
675323 Niranjan 675325 Adithya 675326
Another name space.
This is one name space.
Name - value pair is called Dictionary.
30
An object (variable, functions etc.) defined in a
namespace is associated with that namespace. This
way, the same identifier can be defined in
multiple namespaces.
Google K.M. Abraham.
Who is ????????????? ???????(K M Abraham)
He is a member of ????????????? family.
Object in that Namespace
Name of Namespace
gtgtgt math. sqrt(25) Output 5 gtgtgt
math.pi Output 3.141592653589793
31
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.
2. Place math. (Namespace) before function name.
  1. import math

Name of Namespace
Object in that Namespace
?
?
X sqrt(25)
X math.sqrt(25)
32
No math module in Local Scope.
gtgtgt locals() '__name__' '__main__', '__doc__'
None, '__package__' None, '__loader__' ltclass
'_frozen_importlib.BuiltinImporter'gt, '__spec__'
None, '__annotations__' , '__builtins__'
ltmodule 'builtins' (built-in)gt gtgtgt import
math gtgtgt locals() '__name__' '__main__',
'__doc__' None, '__package__' None,
'__loader__' ltclass '_frozen_importlib.BuiltinImp
orter'gt, '__spec__' None, '__annotations__' ,
'__builtins__' ltmodule 'builtins' (built-in)gt,
'math' ltmodule 'math' (built-in)gt gtgtgt
math module imported into local scope.
A new namespace is setup for importing modules.
33
?
gtgtgt help(math) Traceback (most recent call last)
File "ltpyshell1gt", line 1, in ltmodulegt
help(math) NameError name 'math' is not
defined gtgtgt import math gtgtgt help (math) Help on
built-in module math NAME
math DESCRIPTION This module provides access
to the mathematical functions defined by the
C standard.
Error happened. Because you called help before
'Import Math
?
Import module, before using math, cmath, random,
webbroser, urllib modules.
34
math.
import math abs ( No ) and fabs ( No ) 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. gtgtgt abs(-5.5) gtgtgt
abs(5) Output 5.5 5 gtgtgt math.fabs(5) gtgtgt
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. gtgtgt math.factorial(5) gtgtgt
math.factorial(-5) Output 120 gtgtgt
math.factorial(5.5)
FUNCTIONS.
Abs() is built-in function.
Wrong use
Right use
?
?
35
fmod ( x, y )
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?
gtgtgt import math gtgtgt math.fmod(10.32,3) 1.32
????.???? ?? 3 39 ?????????????????? 1.32
What is the remainder when 11.5 is divided by 2.5?
gtgtgt import math gtgtgt math.fmod(11.5,2.5) 1.5
????.?? ??.?? 2.5 410 ??????????????????
1.5
36
modf (float value)
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?
gtgtgt import math gtgtgt math.modf(math.pi) (0.1415926
5358979312, 3.0) gtgtgt a , b math.modf(math.pi)
a 0.14159265358979312, b 3
Integer part
Fractional part
Tuple data type
Using Multiple Assignment
Like a,b,c 10, 20, 30
37
Statistics module provides 23 statistical
functions. Some of them are discussed
here. Before using them. And call with
statistics. prefix.
import statistics
statistics.mean(list of Nos)
mean() calculate Arithmetic mean
(average) of data.
gtgtgt import statistics gtgtgt statistics.mean(
1,2,3,4,5 ) Output 3 gtgtgt statistics.mean(
1,2,3,4,5,6 ) Output 3.5
Mean is calculated as
Sum of Values Count of Values
38
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.
gtgtgt import statistics gtgtgt a 10,20,25,30,40 gtgtgt
statistics.median(a) Output 25 a 10, 20,
25,30, 40, 50 gtgtgt statistics.median(a) Output
27.5
Here ,number of values is 5, an odd No, So
returns the middle value
If the number of elements is an odd number then
look up else looks down.
Here ,number of values is 6, an even No, So
returns the average of middle two values.
39
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. No mode for KANGAROO
gtgtgt import statistics gtgtgt a 1,2,3,2,1,2 gtgtgt
statistics.mode(a) Output 2 gtgtgt
statistics.mode(MAVELIKARA") Output A'
40
random.
import 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
prefix.
random.
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.
Wrong use
?
41
Returns a random float number between 0 and 1. It
has no argument.
random.random ()
gtgtgt import random gtgtgt random.random() Output
0.6024570823770099 gtgtgt int(random.random()100) Ou
tput 60
If you want a random number below 100, multiply
it by 100 and take the integer.
random.randint (Start, End)
Returns a random number in between given range
including start and end. Both arguments are int
type.
gtgtgt import random gtgtgt random.randint(1,100) Output
79 gtgtgt random.randint(100,999) Output 627
If you need a 3 digit otp number, pick a random
number between 100 and 999.
42
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.
Select a letter from your name.
gtgtgt import random gtgtgt 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 from the list.
gtgtgt import random gtgtgt a anil, babu,
Hari, rajan, jacob, Mathew gtgtgt
random.sample(a,3) Output 'babu', 'jacob',
'Hari'
43
The webbrowser module is used to display web
pages through Python program. Import this
module and call webbrowser.open(URL)
Open your Facebook with 2 line codes.
import webbrowser url "https//www.facebook.com/
" webbrowser.open(url) webbrowser.open("https//ma
il.google.com/") webbrowser.open(https//www.yout
ube.com/)
opens mail
opens youtube
44
OUTPUT OF 2 LINE CODE
gtgtgt import webbrowser gtgtgt webbrowser.open("https
//www.slideshare.net/venugopalavarmaraja/")
2 Lines code
Give any address (URL)here.
WOW only 2 Lines. I want to open my mail like
this.
45
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..
Urllib.request.urlopen() Open a website denoted by URL for reading. It will return 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.
46
import urllib.request import webbrowser u
"https//www.slideshare.net/venugopalavarmaraja/"
weburl urllib.request.urlopen(u) html
weburl.read() code weburl.getcode() url
weburl.geturl() hd weburl.headers inf
weburl.info() print("The URL is ",
url) print("HTTP status code ", code
) print("Header returned ", hd ) print("The
info() returned ", inf ) print("Now opening the
url",url ) webbrowser.open_new(url)
Creating QUrl object(HTTP Request Object)
Calling Functions with QUrl Object
Printing Data
Opening Website
47
What we learned so far?
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
How to create our own modules.
48
Write the code on the board in a file and save it
with a name with .py suffix. It becomes a
module.
A module is a Python file that contains a
collection of functions, classes, constants, and
other statements.
49
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.
50
Importing module
Fine, but the computer does a lot of things when
you import a module, without knowing you.
Using Module Name as prefix
I opened another program file and imported MYMOD
(.py). The functions written in the module are
working well.
51
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
52
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.
The locals() function returns a dictionary
containing the variables defined in the local
namespace. Calling locals() in the global
namespace is same as calling globals() and
returns a dictionary representing the global
namespace of the module.Jan 7, 2020
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.
53
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.
.
54
The screenshot on the left shows the module we
created. The screenshot below shows how to import
and use that module.
1 feet 30 cm 1 inch 2.5 cm
The CONVERSION.py module contains 2 functions.
They convert, length in feet and inches to meters
and centimeters and vice versa
Import module
55
Count upto x and multiply with f
  1. Find factorial of a No
  2. Find sum upto a No

Count upto x and add with sum
Import into a new program.
56
Structure of a Module DocString (Documentation
String) Functions Constants/Variables Classe
s Objects Other Statements
1
2
3
4
5
6
None of them are mandatory.
57
Sure, Docstring will help you
def fibi(a, b, n) print ("Fibonacci Series
is ", end"") for x in range(n)
print (ab, end", ") a, b b, ab
Nothing understand. Arguments represents
what? What does 'function' do? What will return?
Docstring or Documentation string is a string
that provides a Documentation or help topic.
(what the function do).
58
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) '''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 (ab, end", ")
a, b b, ab
Docstring/Documentation
All doubts will be gone away when the
documentation string is given.
All doubts will be gone away when the
documentation string is given.
59
When you call help, Docstring (documentation
string) will appear. Documentation string can be
given to functions, classes and modules.
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'.
60
Write this code in a Python file and save.
Goto Python Shell and call help()
61
gtgtgt import MYMOD gtgtgt help(MYMOD) Help on module
MYMOD NAME MYMOD DESCRIPTION This Module
contains 4 functions. 1. add(a,b) -gt Receives
2 Nos and return a b. 2. sub(a,b) -gt
Receives 2 Nos and return a - b. 3. add(a,b)
-gt Receives 2 Nos and return a b. 4.
sub(a,b) -gt 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
Help () function gives documentation about
functions, classes, modules.
Come to Python Shell. Import MYMOD and call
help(MYMOD)
62
This module contains each function (), class,
and data. months "Jan","Feb","Mar","Apr","M
ay","Jun", \ "Jul","Aug","Sep","Oct","No
v","Dec" class Student ''' Just an example
of Python class''' pass def String_Date (d,
m, y) ''' Receives d, m, y as integers and
return String Form ''' if d1 or d21 or
d31 return words monthsm-1
", " str(y)
Docstring
Variables,Constants, Objects
Classes Definitions
Documentation Sting of Class.
Functions Documentation Sting.
Function Definitions
63
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
64
When you get some songs, should you copied all in
desktop?
How many modules we created so far?
No, I will create a folder and copy them.
Four Modules
65
Absolutely right. 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.
66
Packages are folders that contain related
modules and other sub-packages.
The 'package' may contain other sub-packages in
it.
Import modules from them and use as you need.
The package is a way to organize modules and
other resources in a neat and tidy manner.
67
Packages are folders and Modules are files in
them.
Create a folder or directory Inside that folder,
create or move some Module (.py Files) Create a
file named __init__.py in this folder. (It may be
Empty)
1
2
3
68
Collection of modules(.py Files) saved in a
folder are called package. Package and folder
names must be the same.
Packages are like folders and modules are like
files in that folder.
Create folder Package
1
Create folder
Create Module (.py Files) inside the folder
2
Create __init__.py inside this folder.
3
69
Create Folder
Create a folder with the name of the package you
are going to create, in Python Instalation
folder.
1
Create folder Package
You can do this in Windows File Manager Or in
Python using OS Module.
70
What is the name of the folder for the new
package?
Create a package called my_package" to
organize previously learned modules
Both have the same name.
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)
71
OS module provides file management functions
such as getcwd () and mkdir ()
1
Create my_package
Step 1
getcwd() -gt Get Current Working
Directory. mkdir() Make directory (Create folder)
Create a folder named my_package
Getting Current Working Directory(folder)
Creating Folfer.
72
Create folder anywhere using any method. But must
be added to the System path
Create Modules.
Let us try the previous module / file MYMOD.py.
1
Done
import os os.mkdir(MY_PACKAGE)
MY_Package folder created
Step 2
Create one or more modules in this folder. Or
copy/move existing files into this folder.
73
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,)
gtgtgt import os gtgtgt os.mkdir(my_package)
SAVE IN MY_PACKAGE
74
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)
gtgtgt import os gtgtgt os.mkdir
MY 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
75
Step 2 Create Module. MY_MATH Module described in
slide No 55. It contains 2 functions fact(x) ,
add_up_to(x)
MY Package
Count upto x and multiply with f
MYMOD.py
CONVESION.py
SAVE IN MY_PACKAGE
Creating MY_MATH.py
Count upto x and add with sum.
Create __init__.py
76
__init__.py How is it pronounced?
"Underscore underscore init underscore underscore
dot py"
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.
77
__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..
1
2
3
78
Create __init__.py
Not all folders are packages. But all packages
are folders.
All Done
1
MY_Package folder created
import os os.mkdir(MY_PACKAGE)
2
Step 3
MY_MATH.py
Folders become a package when they have
__init__.py file.
3
79
Create __init__.py
Step 3
1
All Done
MY_Package folder created
If the __init__.py file is empty, we can import
the package but cant use it. Because
initialization has not been done. init refers to
initialization. When the Package being
imported, __init__.py automatically execute and
initialize the Package.
2
MY_MATH.py
3
80
Empty/Missing __init__.py
If the __init__.py file is empty or missing, we
can import the package but cant use it. Because
initialization did not happened.
No __init__.py In Content Section
The package cannot be used.
81
Create __init__.py
1
So, write following code in __init__.py
Done
MY_Package folder created
MYMOD.py
import my_package.MYMOD import my_package.CONVERSI
ON import my_package.MY_MATH
CONVERSION.py
2
MY_MATH.py
Creating __init__.py
Save the file in my_package
Step 3
82
What next?
Did you complete all 3 steps?
Import into current project use
Use later in another project.
Yes, Creating Folder, Modules and
__init__.py
Share with others.
Packages are the basic unit for code sharing.
83
What next?
Import Package
There are 3 modules in this package. CONVERSION,
MYMOD and MY_MATH. See how them used.
Import Package
Uses functions in modules
84
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.
85
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.
import math import math.pi
?
Pi' is an object defined in the math
module. Partial import is not possible with the
"Import" statement.
86
Multiple Modules can be imported with one import
statement.
import ltModule1gt, ltModule2gt,
import math import random
import math, random
import my_package.MYMOD,my_package.MY_MATH
But it is not a standard style.
Using 2 statements.
2 in 1 statements.
87
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 cant import partial components.
import math.pi 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.
?
gtgtgt pi Output 3.14 gtgtgt math.pi
?
88
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
89
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.
from ltmodulegt import ltobjectgt
module name act as NameSpace
90
A module (object) can be renamed when it is
imported. And use this nickname(alias) instead of
real name.
Don't worry. Rename it as ulib while importing
it.
urllib! How I pronounce it.
The 'as' clause is used to rename importing
objects.
import ltmodulegt as ltNew Namegt from ltmodulegt
import ltobjectgt as ltNew Namegt
91
The 'as' clause is used to rename importing
objects.
import ltmodule1gt as ltNew Namegt , ltmodule2gt as
ltNew Namegt from ltmodulegt import ltobjectgt as ltNew
Namegt,ltobject2gt as ltNew Namegt
python will support unicode malayalam.
import urllib as ulib import statistics as
stat import math as ?????? from math import
factorial as fact
92
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.
93
The wild card(character) is a letter (asterisk )
used in the sense of all functions and objects.
Can you import all the objects from math module?
import math is it?
from math import import math
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.
94
The base of natural logarithm "e" (Euler's No) is
defined in math. There is a chance to redefine
its value by accident.
What happens if you define e 123?
It will change the existing value.
95
The "Import" statement loads a module into its
own namespace, so you must enter the module name
and dot before their components.
?
gtgtgt import math
gtgtgt 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.
gtgtgt from math import sqrt
?
gtgtgt sqrt(25)
96
"Import" statement loads the whole module into a
new (own) namespace. It is not possible to
import selected components.
Import the whole Module.
New namespace created.
Dot notation needed
Import sqrt() function only.
from .. import" statement loads whole or
selected components into current namespace
Loaded to current namespace
No DOT notation.
97
No crowds. The module components are kept in a
separate box.
All are in separate namespace
All in local scope. Heap of objects
Oh. My God!, All in local scope. Heap of
objects!!!
98
Previously created package my_package contains
3 modules. MYMOD, MY_MATH CONVERSION
How Import Works
Don't think "from...import" is good for nothing.
Everyone is worthy in their own place.
import my_package
Create namespace for the package and create other
3 namespaces under it for each modules (MYMOD,
MY_MATH CONVERSION). Each objects goes to
corresponding modules 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.
99
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.ad
d (10,20)
from statistics import mean as average
Output 3
gtgtgt average( 1,2,3,4,5 )
Despite the many drawbacks, the advantage of
"from .. import" is that we can only import the
items we need
100
Type online in Malayalam and cut and paste.
Write the program. Enjoy programming.
101
This initiative will make sense if you find this
presentation useful. If you find any mistakes
please comment.
Namasthe
Write a Comment
User Comments (0)
About PowerShow.com