UNIT-4 Python

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 41

MODULE AND APPLICATIONS

UNIT-4

:by Gouri Sankar Mishra


[email protected]
EXCEPTION
 An exception in Python is an incident that happens while executing
a program that causes the regular course of the program's commands
to be disrupted. When a Python code comes across a condition it
can't handle, it raises an exception. An object in Python that
describes an error is called an exception.

 When a Python code throws an exception, it has two options: handle


the exception immediately or stop and quit.

 Exceptions versus Syntax Errors


 When the interpreter identifies a statement that has an error, syntax
errors occur. Consider the following scenario:
#Python code after removing the syntax error
string = "Python Exceptions"
We encountered an exception
error after executing this code.
for s in string:
When syntactically valid Python
if (s != o:
code produces an error, this is the
print( s )
kind of error that arises. The
Output: output's last line specified the
if (s != o: name of the exception error code
^ encountered. Instead of displaying
SyntaxError: invalid syntax just "exception error", Python
The arrow in the output shows where the interpreter encountered a displays information about the sort
syntactic error. There was one unclosed bracket in this case. Close of
it exception error that occurred. It
and rerun the program: was a NameError in this situation.
#Python code after removing the syntax error Python includes several built-in
string = "Python Exceptions" exceptions. However, Python
for s in string: offers the facility to construct
if (s != o): custom exceptions.
print( s )
Output:
2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )
NameError: name 'o' is not defined
TRY AND EXCEPT STATEMENT - CATCHING
EXCEPTIONS
 In Python, we catch exceptions and handle them using try
and except code blocks. The try clause contains the code
that can raise an exception, while the except clause
contains the code lines that handle the exception. Let's see
if we can access the index from the array, which is more
than the array's length, and handle the resulting exception.
 The code blocks that potentially produce an error are
inserted inside the try clause in the preceding example.
The value of i greater than 2 attempts to access the list's
item beyond its length, which is not present, resulting in
an exception. The except clause then catches this
exception and executes code without stopping it.
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the array

for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter

except:
print ("Index out of range")

Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
HOW TO RAISE AN EXCEPTION
 If a condition does not meet our criteria but is correct according to the Python
interpreter, we can intentionally raise an exception using the raise keyword. We can use
a customized exception in conjunction with the statement.
 If we wish to use raise to generate an exception when a given condition happens, we
may do so as follows:
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is
{len(num)}" )
Output:
1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3
but is {len(num)}" )
 Exception: Length of the given list must be less than or equal to 3 but is 4
 The implementation stops and shows our exception in the output, providing indications
as to what went incorrect.
ASSERTIONS IN PYTHON
 When we're finished verifying the program, an assertion is a consistency test that we can
switch on or off. The simplest way to understand an assertion is to compare it with an if-
then condition. An exception is thrown if the outcome is false when an expression is
evaluated.
 Assertions are made via the assert statement, which was added in Python 1.5 as the latest
keyword.
 Assertions are commonly used at the beginning of a function to inspect for valid input and
at the end of calling the function to inspect for valid output.

 The assert Statement


 Python examines the adjacent expression, preferably true when it finds an assert statement.
Python throws an AssertionError exception if the result of the expression is false.

 The syntax for the assert clause is − assert Expressions[, Argument]

 Python uses ArgumentException, if the assertion fails, as the argument for the
AssertionError. We can use the try-except clause to catch and handle AssertionError
exceptions, but if they aren't, the program will stop, and the Python interpreter will
generate a traceback.
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)

#Calling function and passing the values


print( square_root( 36 ) )
print( square_root( -36 ) )
Output:
7 #Calling function and passing the values
----> 8 print( square_root( 36 ) )
9 print( square_root( -36 ) )
Input In [23], in square_root(Number)
3 def square_root( Number ):
----> 4 assert ( Number < 0), "Give a positive integer"
5 return Number**(1/2)

AssertionError: Give a positive integer


TRY WITH ELSE CLAUSE
Python also supports the else clause, which should come after every except clause, in the
try, and except blocks. Only when the try clause fails to throw an exception the Python
interpreter goes on to the else block. Example:
# Python program to show how to use else clause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )
Output:
0.25
We cannot divide by zero
MODULAR PROGRAMMING
 Modular programming is the practice of segmenting a single, complicated coding task into
multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we
can build a bigger program by assembling different modules that act like building blocks.
 Modularizing our code in a big application has a lot of benefits.
 Simplification: A module often concentrates on one comparatively small area of the overall
problem instead of the full task. We will have a more manageable design problem to think
about if we are only concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.
 Flexibility: Modules are frequently used to establish conceptual separations between various
problem areas. It is less likely that changes to one module would influence other portions of
the program if modules are constructed in a fashion that reduces interconnectedness. (We
might even be capable of editing a module despite being familiar with the program beyond
it.) It increases the likelihood that a group of numerous developers will be able to collaborate
on a big project.
 Reusability: Functions created in a particular module may be readily accessed by different
sections of the assignment (through a suitably established api). As a result, duplicate code is
no longer necessary.
 Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.
 In Python, modularization of the code is encouraged through the use of functions, modules,
and packages.
MODULES IN PYTHON
 A document with definitions of functions and various statements written in Python is
called a Python module.
 In Python, we can define a module in one of 3 ways:
 Python itself allows for the creation of modules.
 Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
 A built-in module, such as the itertools module, is inherently included in the
interpreter.
 A module is a file containing Python code, definitions of functions, statements, or
classes. An example_module.py file is a module we will create and whose name is
example_module.
 We employ modules to divide complicated programs into smaller, more
understandable pieces. Modules also allow for the reuse of code.
 Rather than duplicating their definitions into several applications, we may define our
most frequently used functions in a separate module and then import the complete
module.

 Let's construct a module. Save the file as example_module.py after entering the
following.
# Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
"""This function will square the number passed to it"""
result = number ** 2
return result
Here, a module called example_module contains the definition of the function square().
The function returns the square of a given number.

How to Import Modules in Python?


In Python, we may import functions from one module into our program, or as we say into,
another module.
For this, we make use of the import Python keyword. In the Python window, we add the
next to import keyword, the name of the module we need to import. We will import the
module we defined earlier example_module.

import example_module
The functions that we defined in the example_module are not immediately imported into
the present program. Only the name of the module, i.e., example_ module, is imported
here.
 We may use the dot operator to use the functions using the module
name. For instance:
 result = example_module.square( 4 )

 print( "By using the module square of number is: ", result )

 Output:
 By using the module square of number is: 16

 There are several standard modules for Python. The complete list of
Python standard modules is available. The list can be seen using the
help command.
 Similar to how we imported our module, a user-defined module, we
can use an import statement to import other standard modules.
 Importing a module can be done in a variety of ways. Below is a list
of them.
Python import Statement
Using the import Python keyword and the dot operator, we may
import a standard module and can access the defined functions within
it. Here's an illustration.

# Python program to show how to import a standard module


# We will import the math module which is a standard module

import math
print( "The value of euler's number is", math.e )

Output:

The value of euler's number is 2.718281828459045


IMPORTING AND ALSO RENAMING
 While importing a module, we can change its name too. Here is an
example to show.
# Python program to show how to import a module and rename it
# We will import the math module and give a different name to it
import math as mt
print( "The value of euler's number is", mt.e )
Output:
The value of euler's number is 2.718281828459045

 The math module is now named mt in this program. In some


circumstances, it might help us type faster in case of modules having
long names.
 Note that now the scope of our program does not include the term
math. Thus, mt.pi is the proper implementation of the module,
whereas math.pi is invalid.
PYTHON FROM...IMPORT STATEMENT
 We can import specific names from a module without importing
the module as a whole. Here is an example.
 # Python program to show how to import specific objects from a
module
 # We will import euler's number from the math module using the
from keyword
 from math import e

 print( "The value of euler's number is", e )

 Output:

 The value of euler's number is 2.718281828459045

 Only the e constant from the math module was imported in this
case.
 We avoid using the dot (.) operator in these scenarios. As follows,
we may import many attributes at the same time:
# Python program to show how to import multiple objects from a
module
from math import e, tau
print( "The value of tau constant is: ", tau )
print( "The value of the euler's number is: ", e )
Output:
The value of tau constant is: 6.283185307179586
The value of the euler's number is: 2.718281828459045

Import all Names - From import * Statement


To import all the objects from a module within the present
namespace, use the * symbol and the from and import keyword.
Syntax:

from name_of_module import *


 There are benefits and drawbacks to using the symbol *. It is not
advised to use * unless we are certain of our particular
requirements from the module; otherwise, do so.
# importing the complete math module using *
from math import *
# accessing functions of math module without using the dot
operator
print( "Calculating square root: ", sqrt(25) )
print( "Calculating tangent of an angle: ", tan(pi/6) ) # here pi is
also imported from the math module
Output:
Calculating square root: 5.0
Calculating tangent of an angle: 0.5773502691896257
LOCATING PATH OF MODULES
 The interpreter searches numerous places when importing a
module in the Python program. Several directories are searched if
the built-in module is not present. The list of directories can be
accessed using sys.path. The Python interpreter looks for the
module in the way described below:

 The module is initially looked for in the current working


directory. Python then explores every directory in the shell
parameter PYTHONPATH if the module cannot be located in the
current directory. A list of folders makes up the environment
variable known as PYTHONPATH. Python examines the
installation-dependent set of folders set up when Python is
downloaded if that also fails.
 # We will import the sys module
 import sys

 # we will import sys.path

 print(sys.path)

 Output:

 ['/home/pyodide', '/home/pyodide/lib/Python310.zip',
'/lib/Python3.10', '/lib/Python3.10/lib-dynload', '',
'/lib/Python3.10/site-packages']

 The dir() Built-in Function


 We may use the dir() method to identify names declared within a
module.
 For instance, we have the following names in the standard module
str. To print the names, we will use the dir() method in the following
way:
 # Python program to print the directory of a module
 print( "List of functions:\n ", dir( str ), end=", " )

 Output:
 List of functions:
 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
SEARCHING
 Searching is a technique to find the particular element is present
or not in the given list.

 There are two types of searching -

 Linear Search
 Binary Search

 Both techniques are widely used to search an element in the given


list.
LINEAR SEARCH
 Linear search is a method of finding elements within a list. It is
also called a sequential search. It is the simplest searching
algorithm because it searches the desired element in a sequential
manner.

 It compares each and every element with the value that we are
searching for. If both are matched, the element is found, and the
algorithm returns the key's index position.
 Concept of Linear Search

 Let's understand the following steps to find the element key = 7 in


the given list.
 Step - 1: Start the search from the first element and Check key = 7
with each element of list x.
 Linear Search in Python

 Step - 2: If element is found, return the index position of the key.


 Step1

 Step2
 Step3

def linear_Search(list1, n, key):


# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
BINARY SEARCH
 A binary search is an algorithm to find a particular element in the
list. Suppose we have a list of thousand elements, and we need to
get an index position of a particular element. We can find the
element's index position very fast using the binary search
algorithm.
 There are many searching algorithms but the binary search is
most popular among them.
 The elements in the list must be sorted to apply the binary search
algorithm. If elements are not sorted then sort them first.
 A set of statements is repeated multiple times to find an element's
index position in the iterative method. The while loop is used for
accomplish this task.
 Binary search is more effective than the linear search because we
don't need to search each list index. The list must be sorted to
achieve the binary search algorithm.
 Let's have a step by step implementation of binary search.
 We have a sorted list of elements, and we are looking for the
index position of 45.
 [12, 24, 32, 39, 45, 50, 54]

 So, we are setting two pointers in our list. One pointer is used to
denote the smaller value called low and the second pointer is used
to denote the highest value called high.
 Next, we calculate the value of the middle element in the array.
# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present,
# else returns -1
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
# for get integer result
mid = (high + low) // 2
# Check if n is present at mid
if list1[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1
# If n is smaller, compared to the left of mid
else:
return mid
# element was not present in the list, return -1
return -1
# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
# Function call
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
Output: Element is present at index 4
BUBBLE SORT
 The bubble sort uses a straightforward logic that works by
repeating swapping the adjacent elements if they are not in the
right order. It compares one pair at a time and swaps if the first
element is greater than the second element; otherwise, move
further to the next pair of elements for comparison.
 Let's understand it by an example -

 We are creating a list of element, which stores the integer


numbers
 list1 = [5, 3, 8, 6, 7, 2]

 Here the algorithm sort the elements -

 First iteration

 [5, 3, 8, 6, 7, 2]

 It compares the first two elements and here 5>3 then swap with
each other. Now we get new list is -
 [3, 5, 8, 6, 7, 2]
 In second comparison, 5 < 8 then swapping happen -

 [3, 5, 8, 6, 7, 2]

 In third comparison, 8>6 then swap -

 [3, 5, 6, 8, 7, 2]

 In fourth comparison, 8>7 then swap -

 [3, 5, 6, 7, 8, 2]

 In fifth comparison, 8>2 then swap-

 [3, 5, 6, 7, 2, 8]

 Here the first iteration is complete and we get the largest element at
the end. Now we need to the len(list1) - 1
 Second Iteration

 [3, 5, 6, 7, 2, 8] - > [3, 5, 6, 7, 2, 8] here, 3<5 then no swap taken


place
 [3, 5, 6, 7, 2, 8] - > [3, 5, 6, 7, 2, 8] here, 5<6 then no swap taken
place
 [3, 5, 6, 7, 2, 8] - > [3, 5, 6, 7, 2, 8] here, 6<7 then no swap taken
place
 [3, 5, 6, 7, 2, 8] - > [3, 5, 6, 2, 7, 8] here 7>2 then swap their position.
Now
 [3, 5, 6, 2, 7, 8] - > [3, 5, 6, 2, 7, 8] here 7<8 then no swap taken
place.
 Third Iteration

 [3, 5, 6, 2, 7, 8] - > [3, 5, 6, 7, 2, 8] here, 3<5 then no swap taken


place
 [3, 5, 6, 2, 7, 8] - > [3, 5, 6, 7, 2, 8] here, 5<6 then no swap taken
place
 [3, 5, 6, 2, 7, 8] - > [3, 5, 2, 6, 7, 8] here, 6<2 then swap their
positions
 [3, 5, 2, 6, 7, 8] - > [3, 5, 2, 6, 7, 8] here 6<7 then no swap taken
place. Now
 [3, 5, 2, 6, 7, 8] - > [3, 5, 2, 6, 7, 8] here 7<8 then swap their position.
 It will iterate until the list is sorted.

 Fourth Iteration -
 [3, 5, 2, 6, 7, 8] - > [3, 5, 2, 6, 7, 8]

 [3, 5, 2, 6, 7, 8] - > [3, 2, 5, 6, 7, 8]

 [3, 2, 5, 6, 7, 8] - > [3, 2, 5, 6, 7, 8]

 [3, 2, 5, 6, 7, 8] - > [3, 2, 5, 6, 7, 8]

 [3, 2, 5, 6, 7, 8] - > [3, 2, 5, 6, 7, 8]

 Fifth Iteration

 [3, 2, 5, 6, 7, 8] - > [2, 3, 5, 6, 7, 8]


# Creating a bubble sort function
def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))
Output: The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]
MATPLOTLIB PACKAGE
 Matplotlib is a python library used to create 2D graphs and plots
by using python scripts. It has a module named pyplot which
makes things easy for plotting by providing feature to control
line styles, font properties, formatting axes etc. It supports a very
wide variety of graphs and plots namely - histogram, bar charts,
power spectra, error charts etc. It is used along with NumPy to
provide an environment that is an effective open source
alternative for MatLab. It can also be used with graphics toolkits
like PyQt and wxPython.

 Conventionally, the package is imported into the Python script by


adding the following statement −

 from matplotlib import pyplot as plt


 Matplotlib Example
 The following script produces the sine wave plot using
matplotlib.
 import numpy as np

 import matplotlib.pyplot as plt

 # Compute the x and y coordinates for points on a sine curve

 x = np.arange(0, 3 * np.pi, 0.1)

 y = np.sin(x)

 plt.title("sine wave form")

 # Plot the points using matplotlib

 plt.plot(x, y)

 plt.show()

 Its output is as follows −

You might also like