0% found this document useful (0 votes)
2 views

Revised Python Modules XI CSc (1)

The document provides an overview of Python modules, libraries, and packages, detailing how to import and use them effectively in programming. It explains the advantages of using modules for code reusability, simplicity, and scoping, and describes various built-in modules such as math, random, and statistics along with their functions. Additionally, it highlights the importance of packages for organizing related modules and includes examples of mathematical operations using these modules.

Uploaded by

bluewoolxaizen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Revised Python Modules XI CSc (1)

The document provides an overview of Python modules, libraries, and packages, detailing how to import and use them effectively in programming. It explains the advantages of using modules for code reusability, simplicity, and scoping, and describes various built-in modules such as math, random, and statistics along with their functions. Additionally, it highlights the importance of packages for organizing related modules and includes examples of mathematical operations using these modules.

Uploaded by

bluewoolxaizen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Know Python Bytes

www.knowpythonbytes.blogspot.com

Mrs. Payal Bhattacharjee, PGT(C.Sc.)


K V No.1 Kanchrapara
KVS-RO(Kolkata)
Unit II: Computational Thinking and Progamming-1
Python Libraries and Modules
 Introduction to Python modules:
 Importing module using 'import <module>' and using from
statement,
 Renaming / Aliasing a module
 Importing math module (pi, e, sqrt, ceil, floor, pow, fabs, sin,
cos, tan);
 Importing random module(random, randint, randrange)
 Importing statistics module (mean, median, mode)
INTRODUCTION TO PYTHON MODULES
• In Python, a module is a simple Python file that contains collections of
functions, classes and variables having a “.py” extension file.
• It is an executable file.
• Python treats the file name as the module names.
ADVANTAGES OF MODULES:
(i) Reusability : It minimizes the development of redundant codes.
(ii) Simplicity: It is simple to reuse a code than to write a program again from the beginning. It
also requires very little code to be written.
(iii) Scoping: A separate namespace is defined by a module that helps to avoid collisions
between identifiers.
For eg. Consider some readymix masala or ready to cook packets,where you just need to
use it and cook. And, by doing that you save the preparation time before cooking. In the
same way, modules(readymix) are imported (brought into) your program to use the
functions of the module in your program(dish being cooked) to save your precious time.
Functions defined in Modules
• A module is a file containing Python definitions (i.e. functions) and
statements.
• Standard library of Python is extended as module(s) to a programmer.
• Definitions from the module can be used within the code of a program.
• To use these modules in the program, a programmer needs to import the
module.
• Once we import a module, we can reference (use), any of its functions or
variables in our code. There are many ways to import a module in our
program, primarily they are:
i. import <module>
ii. from <module> import <objectname>[,<objectname>[…]
STEPS for importing a module OR
for importing a part(specific function) of a module
To reuse/import the functions of a given module i.e. to add a module or part of a
module in the program code, the import and from statements are used
# to import the entire module # imports a function from a module
import <modulename> from <modulename> import <functionname>

OUTPUT
OUTPUT
RENAMING/ALIASING A MODULE
• As per programmer’s requirement, one can rename the name of a
module i.e give a short new alias name to the module.
• It can be used only within the program wherever it has been renamed.
Here, m is the alias
name used for the
math module.

OUTPUT Do you have a


nick name or a
short name? 
LIBRARY
• A Python library is a collection of related modules or reusable codes
under one roof. A library contains bundles of code that can be used
repeatedly in different programs.
• You can use a library conveniently by importing it in your own
program and calling the method/function of that library with period(.)
• Example:
PYTHON STANDARD LIBRARY: It is a library distributed by Python
whenever Python is installed. Commonly used modules present in A Library of different kinds
Python Standard Library are: math,random,statistics modules of books arranged in
different racks within a
pandas library -> A library for data analysis
particular section which
Tkinter library-> A standard GUI library for Python can be issued again and
matplotlib library -> A visualization library in Python for 2D plot again for our studies.
Similarly, codes/modules
of a Python Library which
can be used repeatedly as
per our requirement in our
programs.
PACKAGES
• A Python package refers to a directory of Python module(s). This is a key
feature of organizing modules of one type at one place for the convenience of
programmer. This directory(folder) contains Python modules and also a
constructor(file required for initialization) __init__.py file by which the
interpreter interprets it as a Package. The package is simply a namespace. The
package also contains sub-packages inside it.
• A Python package is also considered as a Python Library.
• Python Packages are collection of Modules under the common namespace. This
common Namespace is actually the directory which is created that contains all
related modules.
• For a directory to become a package, it is COMPULSORY to have at least
__init__.py file to be a part of the folder, even if the __init.py__ file is empty.
PACKAGES contd..
• A python package is normally installed in
C:\Users\....\Python\Python39\Lib\site-packages
• Site packages is the target directory in which all installed Python packages are
placed by default.
• Once you have your package directory ready, you can associate it with Python
by attaching it to Python’s site-packages folder of Python distribution folder.
PACKAGES contd..
• Like all the other modules, the sys module has to be imported with the import statement,
i.e. The sys module provides information about constants, functions and methods of the
Python interpreter. dir(system) gives a summary of the available constants, functions and
methods
• sys.path attribute specifies the directories that the Python Interpreter will look in when
importing modules.
A List [ ] of Directories given by the variable sys.path . It shows the PYTHONPATH
separated by ,comma , where interpreter searches for the module to be imported.

Python
Interpreter
first look in
the current
directory
when
trying to
do an
import.
DATA HANDLING  WORKING WITH
MATH MODULE
Some mathematical functions in math module are:
Write this statement before using the following functions in the
math module.

FUNCTION Prototype Description


(General form)
math.sqrt(num) The sqrt() function returns the
sqrt square root of num.If num <0,
√25 = 5
domain error occurs

math.pow The pow() function returns this


pow (base, exp) raised to exp power i.e., base exp. A 24=16
domain error occurs if base=0 and
1
exp<=0; also if base <0 and exp is not 2-4=
integer. 16
The fabs() functions returns the
=0.0625
math.fabs(num)
fabs absolute value of num i.e. the
magnitude of the number without
sign(+ or -) |18|=18.0
|-18|=18.0
FUNCTION Prototype Description Q) Find :
(General form) math.ceil(2.7) and
math.floor(num) The floor() functions math.floor(2.7)
floor returns the largest
integer value not
greater than num ceiling
2.7
math.ceil(num) The ceil() functions
ceil returns the smallest floor
integer not less than
num.

HINT:
Imagine a room between the two integer points on the y axis where the
given value will lie.
ceiling
Now, the integer value which comes in the ceiling of the room is the
- 2.7
answer for ceil function . Similarly integer value which comes in the floor
floor of the room is the answer for floor function.
FUNCTION Prototype Description
(General form)
math.exp(arg) The exp() function returns the
exp natural logarithm e raised to
the arg power
Value of e is 2.718
math.sin(arg) The sin() functions returns the
sin sine of arg.the value of arg must
be in radians.

math.cos(arg) The cos() functions returns


Cos the cosine of arg. The value of
arg must be in radians
math.tan(arg) The tan() function returns the
tan tangent of arg. The value of
arg must be in radians.
FUNCTION Prototype Description
(General form)
math.log The log() function returns the
log (num,[base]) natural logarithm for num. A
domain error occurs if num is
negative and a range error
occurs if the argument num is
zero.
math.log10(num) The log10() function returns the
log10 base 10 logarithm for num. A
domain error occurs if num is
negative and range error occurs
if the argument is zero.

math.degrees(x) The degrees() converts angle


degrees x from radians to degree

math.radians(x) The radians() converts angle


radians x from degrees to radians
APPLICATION OF MATH MODULE FUNCTIONS IN MATHEMATICAL EXPRESSIONS

Q) Write the corresponding Python Expressions from the mathematical


expressions:
i) ut+1/2 ft2
Ans. u*t+1/2*f*t*t
Alternative way

u*t+(1/2)*f*math.pow(t,2)

**COMPOSITION:
ii) |e2y-x| Composition is an art of combining simple
function(s) to build more complicated ones,
Ans.
math.fabs(math.exp(2*y)-x) i.e., result of one function is used as the input
to another. Here, result of math.exp() is input
to the function math.fabs()
TIME TO SOLVE…………… 
Q1) Give the output for the print Q2) Write the corresponding Python
Expressions from the mathematical
statements expressions:
import math
i) |a|+b >= |b|+a
a=math.pow(2,5)
print(a) ii)

print(math.sqrt(81))
print(math.ceil(12.8)) (iii) Cos(x) - 5x
Tan(x)
print(math.floor(12.8)
print(math.ceil(-38.5)) iv) p+ q
(r+s) 4
print(math.floor(-38.5))
import random module
 The random module is a built-in module in Python to
generate the pseudo-random numbers.
 Random numbers are used in various fields like in
Science, Art, Statistics, cryptography, gaming and
many other fields.
USES OF RANDOM NUMBERS (Some examples)
Captcha
Automatic password generator
Keys for encryption
Random module functions Example
random() The random() method returns a float number between
0.0 to 1.0 i.e. (0<=N<1) This function does not take any initial value as an
argument.Here, in the example, output of a can be 0.0, 0.1,0.12 …and so on
infinite numbers between 0.0 and 1.0 but, it will never get the value 1.0

randint() The randint() function generates random integer values


between the specific integer values. It works only on integer values.
Here, in the example code , it can generate any integer number between 10 to
20,including both the upper limit and lower limit values. The output of b can be
10,11,12,13,14,15,16,17,18,19,20

randrange() / randrange(start ,stop,step)


Randrange() method generates the random number (integer) within the range
specified by start and stop values. It accepts integer values only. By default start
values is 0 and step value is 1.
Here, in the given example code, it can generate any integer number between
10 (lower limit) and 20-1=19 (upper limit-1) Possible Outcomes:
The output of c can be 10,11,12,13,14,15,16,17,18,19 10,14,18 START , STOP , STEP

**HINT: Refer range() method covered under ‘for loop’ section.


EXAMPLES POSSIBLEMODULE
Understanding RANDOM OUTCOMES (RANDOMLY
functions varietiesANYONE)
10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25

0,1,2,3,4,5,6,7,8,9

10,11,12,13,14,15,16,17,18,19,20,21,22,23,24

10,13,16,19,22

Possible Errors in working with random numbers.


Module name random. Randrange()
missing in the beginning function CANNOT
take float numbers
as arguments

randint() function
CANNOT take step values
import statistics
Python statistics module is used to calculate mathematical statistics of numeric
data. For eg. mean(),median(),mode(),stdev() functions under statistics module.
APPLICATION OF STATISTICS
LET US RECALL mean(),median(),mode(),stdev() learnt in Mathematics
Find the mean, median and
mode of the sequence
19,12,9,5,8,5,25,8
SOLUTION:

In Python, we can use a LIST or a


TUPLE as a sequence of numbers.
Stdev() function is to calculate
Standard Deviation.
STATISTICS MODULE FUNCTIONS with EXAMPLES

mean()
median()
mode()
stdev()
Here, St is the alias name used for the statistics module.
Here, L is the List sequence used as the function argument.
Bibliograhy and References
• Google
• Wikipedia
• Quora
• XI Computer Science , By Sumita Arora, Dhanpat Rai
Publication 2020 Edition
• XI Informatics Practices , By Sumita Arora, Dhanpat Rai
Publication 2020 Edition
Stay safe. Stay aware. Stay healthy. Stay alert.
Programming is an ART….
Add your colours to it and make your own

You might also like