Class 12 CBSE Chapter: python libraries.pptx

AravindVaithianadhan 86 views 29 slides Aug 27, 2024
Slide 1
Slide 1 of 29
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29

About This Presentation

Python


Slide Content

Chapter -4 Using Python Libraries

What is Library? A library is a collection of modules that together cater(satisfy) to a specific type of applications or requirements. Python standard library – contains math, cmath , random, statistics, Urllib modules. NumPy library – contain adv. Math functions by creating and manipulating numeric arrays. SciPy – contains algorithmic and mathematical tools for scientific calc. tkinter – provide GUI interface tool kit for applications. Matplotlib – provide tools to produce output of format like plots, graphs, etc.

What is a Module? It is a python file(. py ) containing variables, class definitions, statements and functions related to a particular task. Advantages of modularity: It reduces the high degree of complexity of program. It creates a number of well-defined documented boundaries with in the program. Its contents can be reused on other programs without having to retype the same coding.

Structure of a Python Module? A module contain the following objects: docstrings Variables and constants Classes (templates for objects) Objects (instances of classes) Statements functions

Pythons comes with preloaded modules like random, math modules called as standard library modules. General structure of python module: A module is independent grouping of code and data Can be re-used in other programs Can depend on other modules.

Example module of tempConversion :

The elements of module : Name of the module - tempConversion Module file name – tempConversion.py Objects – Two functions : ( i ) to_centigrade () (ii) to_fahrenheit () Two constants : ( i ) FREEZING_C (ii) FREEZING_F Three doc strings.

Example to import the above modules: >>>import tempConversion To see all docstrings with module name, filename function names and constants: >>> help( tempConversion )

dir () – gives the names of all the objects defined inside the module. >>> dir ( tempConversion ) [‘FREEZING_C’, ‘FREEZING_F’ , ‘__ builtis __’ , ‘__doc__’ , ‘__file__’ , ‘__name__’ , ‘__package__’ , ‘ to_centigrade ’ , ‘ to_Fahrenheit ’ ] Importing modules in a python program: If you want to use the definitions inside a module, then you need to first import the module in your program. To import entire module. Eg. import <module> To import selected object from a module. Eg. from <module> import <object> To import entire module: Import module1,[module2[,…]] Eg. import time – to import time module Eg. import decimals, fractions

Referring to a module’s object is alled dot notation: import tempConversion tempConversion.to_centigrade (98.6) The name of the module is stored inside a constant __name__ >>>import time >>>print ( time.__name __) Output : time Alias name to imported module: Import <module>as < aliasname > Import tempConversion as tc Now to use the object, tc.to_centigrade ()

Importing select selected objects from a module: from <module> import < objectname >[,< objectname >[….]|* To import single object: When single object is imported from a module, you don’t have to prefix the module’s name and the object can be used without modules name. For example, from math import pi print(pi) print( math.pi ) is wrong

To import multiple objects from math import sqrt, pow To import all objects of a module: from < modulename > import * Eg : from math import *

A namespace, in general is a space that holds a bunch of names. It is a name environment holding logical grouping of related objects. For every module, python will create a namespace having its name similar to that of module’s name. ie . Module time’s namespace is also time. When two namespaces come together, to resolve any kind of object-name dispute, python asks you to qualify the names of objects as <module-name>.<object-name>. But within a namespace, an object is referred without any prefix. Python’s processing of import <module> command Namespace : Processing of import <module> command

Processing of import <module> command The code of imported module is interpreted and executed. Defined functions and variables of the module are now available in the program. For imported module, new namespace is setup with the same name as that of the module. Processing of from <module> import <object> command The code of imported module is interpreted and executed. Only the asked functions and variables of the module are now available in the program. no new namespace is created, the imported definition is just added in the current namespace.

Difference between import <module> and from <module> import <object> When there is variable in the program which has a name similar to the one imported via module, then the variable will hide the imported member with the same name because there cannot be two variables with the same name in one namespace.

Let us consider the following example: from tempConversion import * FREEZING_C = -17.5 # this will hide the FREEZING_C of tempConversion module print(FREEZING_C) OUTPUT: -17.5 from tempConversion import * #FREEZING_C = -17.5 # it is made comment print(FREEZING_C) OUTPUT: 0.0

Using Python Standard Library’s Functions and Modules: Using Built-in functions: The built-in functions are part of current namespace of python interpreter. It can be used directly. <function-name>() They are len (), pow(), str(), int(), float(), range(), type(), ets abs(-12.4)  12.4 divmod (7,2)  (3,1) sum( iterable,arg )  sum([2,2.5,3],5) 12.5 max( ( 3,5,7 ) , (7,) )  7 (list/tuple that begins with a higher value is returned) Min( (arg1,arg2,…)) Oct(<integer>)  returns the octal string for the given number. Hex(<integer>)  hexadecimal Int(<number>)  truncates the fractional part and returns only integer Rount (<number>,[ ndigits >])  returns number rounded to ndigits after decimal points

Using Built-in string functions: <str>.join(<string iterable >/list) <str>.split(<string/char>) [note: returns list type and separator character is not included. <str>.replace(<word to be replaced>,<replace word>) Refer page 164 and 165

Some standard library module: Python has a module random that provides random-number generators. >>>import random >>> random.random ()  generate random floating point from 0.0 to less than 1.0 To generate a floating-point number between lower to upper: >>> random.random ()*(u-l)+l Eg : random.random ()*(45-15)+15 Output : 36.59154858443808 >>> random.random ( a,b ) random.uniform ( a,b ) randint () To generate random integer between 15 and 35: >>>import random >>> random.random (15,35) Output: 16

To generate a floating point number in the range that include lower and upper limit: To generate random integer in the range 15 and 35: >>>import random >>> random.uniform (15,35) Output : 20.14278455321457 To generate a random integers in a range with a step value: To generate random integer in the range 15 and 35 with step 3 or 0..235: >>>import random >>> random.randrange (15,35) Output : 21 >>> random.randrange (235) Output : 90

Using string module – some useful constants available in string module. import string # used for constants and functions in this module. string.ascii_letters  returns ASCII letters (alphabets lower and upper case) string.ascii_lowercase / ascii_uppercase string.digits  ‘0…9’ string.hexdigits  ‘0…f/F’ string.octdigits  ‘0…7’ string.punctuation  all special characters (!@!#$%$^%&^*....:”?+_({[}]

PACKAGE / LIBRARY There are numerous libraries available which you can install and use in your programs. Some such libraries are NumPy, SciPy, tkinter etc. In fact, most of the times library and package terms are used interchangeably. P ackage is collection of Python modules under a common namespace, created by placing a different modules on a single directory along with some special files (such as __init__.py) In a directory structure, in order for a folder (containing different modules i.e., . py files) to be recognized as a package, a special file namely _init__.py must also be stored in the folder, even if the file_init__.py is empty.

PACKAGE / LIBRARY A library can have one or more packages and subpackages. simple libraries that can be called package interchangeably. Structure of a Package As you know that Python packages are basically collections of modules under common namespace. This common namespace is created via a directory that contains all related modules. In order for a folder containing Python files to be recognized as a package, an __init__.py file (even if empty) must be part of the folder. 

PACKAGE / LIBRARY Procedure For Creating Packages Decide about the basic structure of your package : Deciding the package name(folder with the name will be created) and modules and subfolders (that serve as sub packages. (Refer prev. slide) Create the directory structure having folders with names of package and subpackages. For example: LibrComputerSubjects Inside this folder, create files/modules, i.e., the . py files and subfolders with their own . py files. Now our topmost folder has the package name as per above figure and subfolders have names as the subpackages (as per adjacent figure). But, still it is not a package as __ init __ in not in the folder.

PACKAGE / LIBRARY Procedure For Creating Packages 3. Create_init__.py files in package and subpackage folders. Create an empty file and saved it as "_init__.py" and then copied this empty_init__.py file to the package and subpackage folders.   4. Associate it with Python installation. This can be done by attaching it to Python's site-packages folder of current Python distribution in your computer. Importing of library and package in Python can be done only if it is attached to its site-packages folder. ( i ) In order to check the path of the site-packages folder of Python, on the Python prompt, type the following two commands,

PACKAGE / LIBRARY Procedure For Creating Packages import sys print ( sys.path ) The sys.path attribute gives an important information about PYTHONPATH, which specifies the directories that the Python interpreter will look in when importing modules. [‘ ‘, 'C:\\Users\\admin\\ AppData \\Local\\Programs\\Python\\Python312\\Lib\\site-packages’] first entry in PYTHONPATH is ‘ '. It means that the Python interpreter will first look in the current directory when trying to do an import. If the asked module/package is not found in current directory, then it check the directory listed in PYTHONPATH. (ii) Once you have figured out the path of site-packages folder, simplest way is to copy your own package-folder (e.g., LibrComputerSubjects that we created above) and paste it in this folder.

PACKAGE / LIBRARY Procedure For Creating Packages 5. After copying your package folder in site- adha site-packages folder of your current Python installation, now it has become a Python library so that now you can import its modules and use its functions. Using/Importing Python Libraries: To use an installed Python library you need to do the following: 1. Import the library using import command: import <full name of library> 2. Use the functions, attributes etc. defined in the library by giving their full name.

PACKAGE / LIBRARY Workout the example given in page 172. Create python modules like details.py, that contains the function ‘def SubjectsList ()’ Create python module like ‘CSXI.py’, ‘CSXII.py’ in subfolder “ ComputerScience ” of package folder “ LibrComputerSubjects ” . Create python module like ‘IPXI.py’, ‘IPXII.py’ in subfolder “ InformaticsPractices ” of package folder “ LibrComputerSubjects ”. Include “__init__.py” in all subfolders to make it as package.

THANK YOU
Tags