UNIT-4 Python
UNIT-4 Python
UNIT-4 Python
UNIT-4
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:
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)
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.
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.
import math
print( "The value of euler's number is", math.e )
Output:
Output:
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
print(sys.path)
Output:
['/home/pyodide', '/home/pyodide/lib/Python310.zip',
'/lib/Python3.10', '/lib/Python3.10/lib-dynload', '',
'/lib/Python3.10/site-packages']
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.
Linear Search
Binary Search
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
Step2
Step3
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 -
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]
[3, 5, 6, 8, 7, 2]
[3, 5, 6, 7, 8, 2]
[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
Fourth Iteration -
[3, 5, 2, 6, 7, 8] - > [3, 5, 2, 6, 7, 8]
Fifth Iteration
y = np.sin(x)
plt.plot(x, y)
plt.show()