60% found this document useful (10 votes)
35K views7 pages

Class 12 Python Libraries Overview

This document discusses Python libraries, modules, and how to create and use libraries in Python programs. It provides examples of common Python standard libraries like random and string. It also explains how to create your own Python package by structuring files and directories with an __init__.py file. Lastly, it notes that libraries can be imported and their functions used by giving the full library name.

Uploaded by

Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
60% found this document useful (10 votes)
35K views7 pages

Class 12 Python Libraries Overview

This document discusses Python libraries, modules, and how to create and use libraries in Python programs. It provides examples of common Python standard libraries like random and string. It also explains how to create your own Python package by structuring files and directories with an __init__.py file. Lastly, it notes that libraries can be imported and their functions used by giving the full library name.

Uploaded by

Kabir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Notes
  • Importing Modules in a Python Program
  • Using Python Built-In Functions
  • Creating A Python Library
  • Using/Importing Python Libraries

USING PYTHON LIBRARIES

Notes
Library
Library is a collection of models and packages that together cater to a specific type of
applications or requirements. A library can have multiple models in it.
Some examples of python libraries are listed below:-
1) Python standard library
-math module
-cmath module
-random module
-statistics module
-Urllib module
2) NumPy library
3) SciPy library
4) tkinter library
5) Malplotlib library
Module
•The act of partitioning a program into individual components (known as modules) is called
as modularity.
•The justification for partitioning a program is that it reduces its complexity to some degree
and it creates a number of well defined, documented boundaries within the program.
•A python module can contain much more than just functions. A python module is a normal
python file (.py file) containing one or more of the following objects related to a particular
task:-
-docstrings
-variables and constants
-classes
-objects

-statements
-functions
1
Importing Modules in a Python Program
Python provides import statement to import modules in a program. The import
statement can be used in two forms:-
1) Importing Entire Module
•The imports statement can be used to import entire module.
Syntax :- import <module 1 >, <module 2>....
Example:-
>>>import time
>>>Import decimals, fractions

•After importing a module, any function or definition of the imported module can be
used as per following syntax:-
<module-name>.<function-name> ()
For example:
>>>import math
>>>[Link](16)

•Imported models can be given alias name.


Syntax:- import <module> as <alias name>
Example:- >>>import math as a
>>>[Link](16)

2) Importing Selected Objects From A Module


•To import some selected items, you can use following syntax:-
from <module name >import<object name>
For example:
>>>from math import sqrt

•To import multiple objects from the module, you can use following syntax :-
from <module name>import<object name>,<object name>,<object name>....
For example:-
>>>from math import sqrt, pi, pow

•To import all items from the module, you can use following syntax:-
from <module name> import *
For example:-
>>>from math import *

Using Python Standard Libraries Functions And Modules

2
Python standard library is very extensive that offers many built-in functions. this
library is by default available so it don’t need to be imported separately.
1) Using Python Built In Functions
Python's built in Mathematical Functions
Python provides many mathematical built in functions that are given below:-

i) len():- Returns the length of a sequence or iterable e.g., lenf'abc") gives 3.

ii) pow():- Returns when a and b are given as arguments, e.g., po'v(3' 4) gives
81.

iii) str():- Converts a number to a string, e.g., str(12) will give '12' and str(12.4) will
give '12.4'.

iv) int():- Converts an integer-convertible string to integer, e.g., int('12') will give
12.

v) float():- Converts a float-convertible string to integer, e.g., float('12.2') will give


12.2.

vi) range():- Returns an immutable sequence type, e.g., range(3) will give
sequence 0, 1, 2.

vii) type():- Returns the data type of passed argument, e.g., type(12) will give
<class 'int'>.

Python's Built in String Functions


i) <Str>.join(<string iterable>)
•It joins a string or character (i.e., <str>) after each member of the string
iterator i.e., a string based sequence.
ExampleExample:-
>>>"***".join("Hello")
'H***e***l***l***o'

>>>"***". join (("Hello", "Python"))


'Hello***Python'

ii) <Str>.split(<string/char>)
•It splits a string (i.e., <str>) based on given string or character (i.e.,
<string/char>) and returns a list containing split strings as members.
ExampleExample:-
>>>"I Love Python". split()
['I', 'Love', 'Python']
3
>>>"I Love Python". split ("o")
['I L','ve Pyth','n']

iii) <Str>.replace(<word to be replaced>, <replaced word>)


•It replaces a word or part of the string with another in the given string <str>.
Example:-
>>>"I Love Python". replace ("Python", "Programming")
"I Love Programming"
2) Working With Some Standard Library Modules

Using Random Module


Python has module random that provides random number generators. To use
random number generators in Python program, random module needs to be
imported using import command, e.g., import random

i) random () : - It returns a random floating point number N in range [0.0,1.0] ,


i.e., 0.0 ≤ N < 1.0.
Example:-
>>>import random
>>>print([Link]())
0.022472947483

ii) randint (a, b) : - It returns a random integer N in the range (a, b) , i.e. , a ≤ N ≤
b (both range-limit are inclusive).
Example:-
>>>print([Link](15, 35))
16

iii) [Link](a, b) : - It returns a random floating point number N such that,


a ≤ N ≤ b for a ≤ b and
b ≤ N ≤ a for b < a.
Example:-
>>>[Link](11, 55)
41.38562846284629

iv) [Link](stop) or [Link](start, stop, [ steps]) : - It returns


a randomly selected element from range ( start, stop, step ) .
Example:-
>>>[Link](23, 47, 3)
38
Using String Module

4
Python has module by the name string that comes with many constants and
classes. To use any of the constants/functions defined in the string module, it
needs to be imported, e.g., import string

i) string.ascii_letters :- it returns a string containing all the collection of


ASCII letters.

ii) string.ascii_lowercase :- it returns a string containing all the lowercase


ASCII letters, i.e., 'abcdefghijklmnopqrstuvwxyz'.

iii) string.ascii_uppercase :- it returns all the uppercase ASCII letters, i.e.,


,ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

iv) [Link] :- it returns a string containing all the digits Python allows,
i.e., the string '0123456789'.

v) [Link] :- it returns a string containing all the hexadecimal digits


Python allows, i.e., the string '0123456789abcdefABCDEF'.

vi) [Link] :- it returns a string containing all the octal digits Python
allows, i.e., the string '01234567'.

vii) [Link] :- it returns a string of ASCII characters which are


considered punctuation characters, i.e., the string ‘!”#$%’()*+,-
./:;?@[\]^_‘{|}~’

viii) capwords(<str>, [sep=None|) :- it splits the specified string <Str> into


words using <Str>.split( ). Then it capitalizes each word using
<Str>.capitalize( ) function. Finally, it joins the capitalized words using
<Str>.join().

If the optional second argument sep is absent or is None, it will remove


leading and trailing whitespaces and all inside whitespace characters
are replaced by a single space.

Creating A Python Library


As there are numerous libraries available which can be installed and used in
programs such as NumPy, SciPy, tkinter etc, we can create our own libraries.
Package

5
• A package is a collection of python module under a common name space, created
by placing different modules on a single directory along with some special files (such
as __init__.py). A library can have one or more packages and subpackages.
•In a directory structure in order for a folder (containing different modules i.e., .py
files) to be recognised as a package, a special file namely __init__.py must also be
stored in the folder even if the file __init__.py is empty.
Structure of a Package
As you have read above that an __init__.py file must be part of the folder for python
files to be recognised as a package.

Procedure For Creating Packages

i) Create a new folder named D:\MyApp.


ii) Inside MyApp, create a subfolder with the name 'mypackage'.
iii) Create an empty __init__.py file in the mypackage folder.
iv) Using IDLE, create module [Link] in mypackage folder.
Example:-
def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

The package is ready now. Now we can import it’s modules and use its
functions.

6
Using/Importing Python Libraries

To use and install python library you need to do the following:

i) Import the library using import command:


Import <full name of library>
ii) Use the functions, attributes etc. defined in the library by giving their full
name.

Common questions

Powered by AI

The capwords() function in the string module splits a given string into words, capitalizes the first letter of each word, and then joins them back into a single string, effectively applying title casing. It replaces any sequence of whitespace characters with a single space, and removes leading and trailing spaces by default. A practical scenario for its use might be formatting the names of people or titles of publications in documents and graphical user interfaces to maintain stylistic consistency .

The 'random' module in Python can generate random numbers in several ways, including random floating-point numbers using random(), random integers within a specific range using randint(a, b), and random floating-point numbers within a customizable range using uniform(a, b). Additionally, random.randrange() can be used to select a random element from a specific range (start, stop, step). These functionalities have practical applications in simulations, gaming (e.g., generating random events), security (e.g., generating random passwords), and statistical sampling .

Import statements enhance the functionality and flexibility of Python programming by allowing developers to include and utilize external modules and libraries within their programs. This capability enables code reusability and modular design since entire modules or specific functions can be imported as needed. Importing specific functions or entire modules reduces redundancy and promotes efficient use of pre-existing resources. Additionally, aliasing imports allow for more readable code when modules have long or complex names .

String manipulation functions like join(), split(), and replace() are crucial for text data processing in Python. The join() function allows for the concatenation of strings with a specific separator, which is useful in formatting data outputs. The split() function can divide strings into a list based on a specified delimiter, enabling efficient parsing and processing of text data. The replace() function facilitates text data cleaning by substituting specific substrings with desired alternative values. Combined, these functions support comprehensive data cleaning, transformation, and preparation tasks in text processing workflows .

Creating your own library in Python involves organizing related Python modules into a package with a common namespace, usually within directories structured with an __init__.py file. This enables you to encapsulate and reuse code efficiently across different projects. The benefits include improved code maintainability and modularity, as you can update the library separately from the main application logic. It facilitates collaboration by allowing other developers to leverage your library's functionalities, fostering community development and code sharing .

Modularity in Python programming is significant because it reduces the complexity of software development by partitioning a program into individual components called modules. This approach aids in managing and understanding large codebases by defining clear boundaries within the program, making the code more organized and reusable. By creating well-defined, documented boundaries, modularity allows developers to focus on separate parts of the program independently, facilitating easier debugging and maintenance .

Python packages are collections of modules that are organized under a common namespace, indicated by directories with an __init__.py file. The structure of a package allows for a hierarchical organization of modules, making it easier to manage and navigate large projects. Packages enable sectioning off of related functionality into distinct parts, promoting code reuse and simplifying distribution. This structure allows developers to build libraries with multiple related functionalities and encourages in-built modularity within projects, facilitating maintainability and collaboration .

Using alias names for imported modules or functions can enhance code readability and maintenance by shortening long or complex names, making the code more concise and easier to read. It also helps prevent naming conflicts by allowing the renaming of a function or module that might clash with existing code. However, excessive use of aliases or non-descriptive alias names can obscure the understanding of code for developers unfamiliar with the specific aliases, potentially increasing maintenance difficulty. It is crucial to strike a balance by choosing clear and meaningful alias names .

Using built-in functions from the Python standard library significantly reduces development time and resource use by providing pre-optimized and tested implementations of common functionalities. This avoids the need to manually code and debug these functions, allowing developers to focus on the unique aspects of their projects. The extensive range of available functions enables quick and efficient handling of tasks, promoting rapid prototyping and development. Additionally, leveraging the standard library ensures compatibility and reduces the risk of introducing bugs associated with implementing custom solutions .

The __init__.py file plays a crucial role in Python packages by indicating that the directory it resides in is a package. This special file is required for the Python interpreter to recognize the folder as a package and can also be used to execute initialization code for the package. Although the file can be empty, it is essential for maintaining the package structure and often is used to specify which modules should be accessible when the package is imported .

You might also like