0% found this document useful (0 votes)
5 views28 pages

Lecture24 25 Unit5 1 Modules and Libraries

The lecture covers the concept of modules and libraries in Python, explaining how programs can be structured using modular programming. It details how to create and import modules, as well as the use of standard and third-party libraries like NumPy and Matplotlib. The document emphasizes the importance of modularity in simplifying complex coding tasks and provides examples of importing specific functions from modules.

Uploaded by

bhuvana2405blue
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
0% found this document useful (0 votes)
5 views28 pages

Lecture24 25 Unit5 1 Modules and Libraries

The lecture covers the concept of modules and libraries in Python, explaining how programs can be structured using modular programming. It details how to create and import modules, as well as the use of standard and third-party libraries like NumPy and Matplotlib. The document emphasizes the importance of modularity in simplifying complex coding tasks and provides examples of importing specific functions from modules.

Uploaded by

bhuvana2405blue
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
You are on page 1/ 28

Course Code: CSD106A

Course Title: Programming in Python

Lecture No. 24&25 :


Modules and Libraries in Python
Delivered by: Dr. Anitha Kumari S D

1
Lecture Intended Learning Outcomes

At the end of this lecture, student will be able to

• Understand the concept of modules and libraries in python

• Use modular programming using functions

2
Contents

• Modules, User-defined modules, Standard modules, Libraries

3
Structure of Python program
• Python program consists of multiple text files containing Python statements

• Program is structured as main file (top-level file) along with zero or more
supplemental files known as modules in Python

• Main file: Main flow of control of program

• Module files define tools intended for use in other files

• A file import a module to gain access to the tools it defines

4
Structure of Python program

Ref: Learning Python by Mark Lutz 5


Modules in Python
• Modular programming: Segmenting a single, complicated coding task (program) into
multiple, simpler, easier-to-manage sub-tasks

• A program can be divided into individual components/sub-tasks known as modules

• A module is a file containing Python definitions and statements

• Any single Python file with the *.py extension can be called as module

• It contains a set of functions, classes and variables that can be used by other Python
programs

• Definitions from a module can be imported into other modules or into the main module

6
Modules in Python
Modules can be defined in Python in 3 ways:

• Python allows for the creation of modules by the user

• Module can be written in C programming language and then dynamically inserted


at run-time

• A built-in module inherently included in the interpreter

7
Modules in Python
Defining/Creating a module in Python:

# module definition

# function square will square the number passed as the input

>>>def square(number):

result=number**2

return result

• Save this module as example_module.py file

• Module is created
8
Modules in Python
Importing a module in Python: Functions from one module can be imported to
another program/module using the keyword import
# importing the function square to another file or program
>>>import example_module # module is imported
# to call the function square() within the module
>>>x=example_module.square(6) # use a dot operator to call the respective
function
>>>print('The output of the square fn in module is ', x)
Output is : The output of the square fn in module is 36
9
Importing modules in Python program
• file b.py defines a function spam for external use

>>>def spam(text):

print(text)

• If a.py wants to use function spam:

>>>import b # This statement gives the file a.py access to the file b.py or it means
load b.py and give access to all its attributes

>>>b.spam(‘python’) # Fetch the value of the name spam(here function) that is


inside the file b.py
10
Standard Modules in Python
• Several standard modules for Python (Can be seen by typing >>>help('modules’))

• To get more information about any module (>>> help(module name))

>>>help('matplotlib’)

• Standard modules can be imported using an import statement

>>> import math # This statement imports/fetches a standard Python module


math as a whole

>>>print(math.pi) #Printing the value of pi within the module math

Out: 3.141592653589793
11
Standard Modules in Python
>>>import math

>>>dir(math)

• Built-in function dir() is used to find out which names a module defines

• Eg: 'acos’, 'acosh’, 'asin’, 'asinh’, 'atan’, 'atan2’, 'atanh’ etc

• While importing a module, its name can be changed

>>>import math as mt # here, the math module is imported as mt

>>>print( "The value of pi is ", mt.pi )

Output is: The value of pi is 3.141592653589793


12
Importing modules in a Python program
• The name of the module is stored inside a constant __name__(prefix and suffix
have two underscores)

>>>import math,cmath

>>>print(math.__name__)

math

Module can also be imported as :

>>>import math as calculation

13
Standard Modules in Python
Import statement can be used in two ways to import modules in a program:

1. Import entire module import <module name>

>>>import math

>>>import math, numpy

The way of referring to an object in a module is called dot notation eg: math.sqrt()

2. Import specific names from a module without importing the module as a


whole from <module name> import <object name>

14
from...import Statement in Python
To import selected objects from <module name> import <object>

>>>from math import sqrt

If this command is used for importing, do not use module name with imported object as
imported object is a part of the program

>>>print(pi) #Do not use print(math.pi)

To import multiple objects

>>>from math import pi, sqrt, pow

To import all objects of a module

>>>from math import * # All variables can be used without prefixing module name
15
dir() Built-in Function in Python
dir(): To identify names declared within a module

>>>print(dir(math), end=‘ ‘)

print(dir(math), end=' ')

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',


'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist',
'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians',
'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp’]
16
dir() Built-in Function in Python
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh',
'asin', 'asinh', 'atan’,
>>>print(math.__doc__)
Output: This module provides access to the mathematical functions defined by the
C standard.
>>>print(math.__name__)
Output: math
>>>print(math.sin)
Output: <built-in function sin>
17
Namespaces in Python
• Objects are represented by names or identifiers called variables

• A namespace is a dictionary containing the names of variables (keys) and the


objects that go with them (values)

• Local and global namespace variables can be accessed by a Python statement

• When two variables with the same name are local and global, the local variable
takes the role of the global variable

• Global statement should be used before a value is assigned to a global variable


inside of a function
18
Namespaces in Python
>>>Number = 204
>>>def AddNumber():
global Number
Number = Number+200
print('The value of the number is ', Number)
print('Out side the function the value of number is ', Number)
AddNumber()
Output: Out side the function the value of number is 204
The value of the number is 404
19
Namespaces in Python
>>>Number = 204
>>>def AddNumber():
Number = Number+200
print('The value of the number is ', Number)
print('Out side the function the value of number is ', Number)
AddNumber()
Output: Out side the function the value of number is 204
line 3 in AddNumber (Number = Number+200)
UnboundLocalError: cannot access local variable 'Number' where it is not associated
with a value
This error occurs as the value of the local variable is not declared or not declared as
global
20
Packages in Python
• Structures Python’s module namespace by using “dotted module names”
• Module name A.B designates a submodule named B in a package named A
• Example: A collection of modules handling sound data may have different
formats, effects, filters etc.
• Package can import individual modules from the package eg: sound.effects.echo
• This loads the submodule sound.effects.echo
• Alternate way is
>>>from sound.effects import echo
• Import statement first tests whether the item is defined in the package 21
Libraries in Python
• Some modules imported to the program are provided by Python itself and not
the files which we code

• Python has large collection of utility modules known as standard library

• Example: random module function randint()

>>>from random import randint()

>>>randint(1,6)

Out: 5

22
Libraries in Python
• A library refers to a collection of modules that together cater to a specific type of
applications

• Commonly used Python libraries include:

• Python standard library

• NumPy library

• SciPy library

• tkinter library

• Matplotlib library
23
Libraries in Python
• Python standard library: Available in default, no need to import it separately

• Other libraries are third party packages and need to be imported

• Commonly used Python libraries include:

• Python standard library

• NumPy library

• SciPy library

• tkinter library

• Matplotlib library
24
Libraries in Python
Python standard library includes:

math module: Mathematical functions eg: math.factorial(n)

cmath module: Mathematical functions for complex numbers eg: cmath.sqrt()

random module: Generate pseudo-random numbers eg: random.randint(3,17)

statistics module: Statistical functions eg: statistics.mean([1, 2, 3, 4, 4])

urllib module: URL handling functions to access websites within the program

eg: urllib.request.urlopen

25
Other Libraries in Python
NumPy library : Provides advance math functionalities and tools to create numeric
arrays

SciPy library: Offers algorithmic and mathematical tools for scientific calculations

tkinter library: Python user interface toolkit and helps to create user-friendly GUI
interface for different types of applications

Matplotlib library: Functions and tools to produce plots, charts, graphs

26
Summary
• A program can be divided into individual components/units known as modules
• A module is a file containing Python definitions and statements
• Any single Python file with the .py extension can be called as module
• Python provides import statement to import modules as a whole in a program
import math
• Import specific names from a module without importing the module as a whole
also is possible from math import sqrt
• A library refers to a collection of modules that together cater to a specific type of
applications
27
References
https://www.javatpoint.com/python-modules

28

You might also like