Faculty Python Lab Manual
Faculty Python Lab Manual
Laboratory Manual
(Faculty Copy)
1|Page
Department of Information Technology
Vision
Mission
To create a healthy environment for the development of innovative professional and researchers
to fulfill its commitment to research & education of the highest quality with industry requirement
and social acceptance at large.
2|Page
Program Educational Objectives (PEOs)
The broader objective of IT Department is to transform the students admitted to the program into
globally competitive professionals having sound knowledge of fundamentals and capable with
core competency in logical & computation analysis to solve Engineering Problems. The detailed
Program Educational Objectives (PEOs) are as follows:
PEO 1: To impart exhaustive knowledge to the students in all the sub – domains of
Information Technology and the fast evolving IT tools to:
a) Take up key assignments in IT and associated industries.
b) Undertake and excel in higher studies and Research & Development in
IT related fields and Management.
PEO 2: To impart solid foundation in Computational Intelligence, Science and
Interdisciplinary courses.
PEO 3: To design & develop novel products and innovative solutions for real life
problems in Information Technology field and related domains.
PEO 4: To inculcate a conviction in the students to believe in self, impart professional
and ethical attitude, nurture to be an effective team member, infuse leadership qualities,
build proficiency in soft – skills and the abilities to relate Engineering with the social issues.
PEO 5: To provide a conducive and disciplined Academic environment, quality of
teaching with innovative & modern methods of pedagogy establishing the relevance of technical
education as per the needs of the industry and society at large.
3|Page
Program Outcomes (POs)
4|Page
PO-12:Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Course PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-9 PO-10 PO-11 PO-12
Outcomes
CO1 2 3 2 3 2 1 1 1 2 2 1 1
CO2 3 2 3 2 2 1 1 1 2 1 2 2
CO3 2 2 3 2 2 1 1 1 2 2 2 1
CO4 2 2 2 2 2 1 1 1 2 1 2 1
CO5 2 2 3 1 2 1 1 1 2 1 2 1
PSO-1: An ability to specify, analyze & design a usable computing system that efficiently
utilizes system software and hardware to cover current user requirement in a socially and
economically acceptable form.
PSO-2: An ability to state, design and implement a secure and reliable information
communication system by using concepts of computer networks, network security, information
theory and parallel algorithm.
PSO-3: An ability to state, design and implement knowledge based discovery and machine based
learning in computer system by using the various concepts of soft computing, neural networks,
image processing, digital system design and artificial intelligence.
PSO-4: An ability to analyze and design an efficient information management system which
uses the concepts & tools of databases, data mining and information coding and deliver
technological solutions for the end users.
5|Page
Course Objectives (COs)
CO 1 To read and write simple Python programs. K1, K2
CO 3 To define Python functions and to use Python data structures –- lists, tuples, K3
dictionaries
List of Experiments
1. To write a python program that takes in command line arguments as input and
print the number of arguments.
2. To write a python program to perform Matrix Multiplication.
3. To write a python program to compute the GCD of two numbers.
4. To write a python program to find the most frequent words in a text file.
5. To write a python program find the square root of a number (Newton’s method).
6. To write a python program exponentiation (power of a number).
7. To write a python program find the maximum of a list of numbers.
8. To write a python program linear search.
9. To write a python program Binary search.
10. To write a python program selection sort.
11. To write a python program Insertion sort.
12. To write a python program merge sort.
13. To write a python program first n prime numbers.
14. To write a python program simulate bouncing ball in Pygame.
6|Page
Tools & Software / Reference Material
Python 3.6.4
Anaconda 3 (64 bit)
Reference Websites
https://docs.python.org/2/library/functions.html
https://www.programiz.com/python-programming/methods/built-in/type
https://pypi.python.org/pypi
https://www.anaconda.com/
Reference books
7|Page
List of Experiments
Experiment 1
8|Page
Objective: To write a python program that takes in command line arguments as input and print
the number of arguments.
Description
The command line arguments must be given whenever we want to give the input before the start
of the script, while on the other hand, input() is used to get the input while the python program /
script is running.
Students will be able to learn how to use the command line argument.
Algorithm:
1. Command line arguments are stored in the form of list in sys.argv
2. Print the name of file
3. Print the first argument after the name of file
Code:
import sys
argumentList = sys.argv
print argumentList
print sys.argv[0]
print sys.argv[1]
Experiment 2
Flow Chart:
10 | P a g e
11 | P a g e
Algorithm:
1. Start
2. Declare variables and initialize necessary variables
3. Enter the element of matrices by row wise using loops
4. Check the number of rows and column of first and second matrices
5. If number of rows of first matrix is equal to the number of columns of second matrix, go
to step 6. Otherwise, print matrix multiplication is not possible and go to step 3.
6. Multiply the matrices using nested loops.
7. Print the product in matrix form as console output.
8. Stop
Code:
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
12 | P a g e
Experiment 3
Description:
Euclidean algorithm
In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the
smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6.
Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F.
Flow Chart:
Algorithm:
Algorithm is based on the fact that H.C.F. of two numbers divides their difference as
well. In this algorithm, we divide the greater by smaller and take the remainder.
Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The
remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required
H.C.F.
13 | P a g e
Code:
def compute_hcf(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
print("The H.C.F. is", compute_hcf(num1, num2))
14 | P a g e
Experiment 4
Objective : To write a python program to find the most frequent words in a text file.
Algorithm/flowchart:
Variable maxCount will store the count of most repeated word.
Open a file in read mode using file pointer.
Read a line from file. Convert each line into lowercase and remove the punctuation
marks.
Split the line into words and store it in an array.
Use two loops to iterate through the array. Outer loop will select a word which needs to
be count. Inner loop will match the selected word with rest of the array. If match found,
increment count by 1.
If count is greater than maxCount then, store value of count in maxCount and
corresponding word in variable word.
At the end, maxCount will hold the maximum count and variable word will hold most
repeated word.
Code:
count = 0;
word = " ";
maxCount = 0;
words = [];
#If maxCount is less than count then store value of count in maxCount
#and corresponding word to variable word
if(count > maxCount):
maxCount = count;
word = words[i];
15 | P a g e
print("Most repeated word: " + word);
file.close();
Experiment 5
Objective : To write a python program find the square root of a number (Newton’s method).
16 | P a g e
Description:
Starting from initial guess x1, the Newton Raphson method uses below formula to find next value
of x, i.e., xn+1 from previous value xn.
Code:
# Python3 code for implementation of Newton
# Raphson Method for solving equations
# An example function whose solution
# is determined using Bisection Method.
# The function is x^3 - x^2 + 2
def func( x ):
return x * x * x - x * x + 2
# Derivative of the above function
# which is 3*x^x - 2*x
def derivFunc( x ):
return 3 * x * x - 2 * x
# Function to find the root
def newtonRaphson( x ):
h = func(x) / derivFunc(x)
while abs(h) >= 0.0001:
h = func(x)/derivFunc(x)
# x(i+1) = x(i) - f(x) / f'(x)
x = x - h
print("The value of the root is : ", "%.4f"% x)
# Driver program to test above
x0 = -20 # Initial values assumed
newtonRaphson(x0)
17 | P a g e
Experiment 6
Description:
An exponent refers to the number of times a number is multiplied by itself. For example, 2 to the
3rd (written like this: 23) means:
2 x 2 x 2 = 8.
18 | P a g e
23 is not the same as 2 x 3 = 6.
Algorithm:
Flow Chart:
Code:
Base = int(input(" Please Enter any Positive Base : "))
Power = int(input(" Please Enter Power Value : "))
output= 1
19 | P a g e
Experiment 7
Description
Input : list1 = [10, 20, 4]
Output : 20
Algorithm
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
Flow Chart
Code:
20 | P a g e
We have three methods for finding max in a list of numbers
1. Using for loop
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
2. Using sorting: Sort the list and select last element
# Python program to find largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# list of numbers
list1 = [10, 20, 4, 45, 99]
# printing the maximum element
print("Largest element is:", max(list1))
21 | P a g e
Experiment 8
Description:
Linear search or sequential search is a method for finding a particular value in a list that checks
each element in sequence until the desired element is found or the list is exhausted. The list need
not be ordered.
Algorithm:
1. Start from the leftmost element of list and one by one compare x with each element of the
list.
2. If x matches with an element, return True and index.
3. If x doesn’t match with any of elements, return False.
Flow Chart:
Code:
def Sequential_Search(dlist, item):
pos = 0
22 | P a g e
found = False
print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))
Experiment 9
23 | P a g e
Description:
A binary search or half-interval search algorithm finds the position of a target value within a
sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer
search algorithm and executes in logarithmic time.
Algorithm:
Flow Chart:
Code:
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
24 | P a g e
Experiment 10
Description: The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the beginning.
Algorithm:
Flowchart:
Code:
# Python program for implementation of Selection
# Sort
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
26 | P a g e
Experiment 11
Description: "Insertion sort is a simple sorting algorithm that builds the final sorted array (or
list) one item at a time. It is much less efficient on large lists than more advanced algorithms
such as quicksort, heapsort, or merge sort."
Algorithm/Flowchart:
27 | P a g e
Code:
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
end while
28 | P a g e
Experiment 12
Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is
considered sorted).
Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist
remaining. This will be the sorted list.
Flowchart:
29 | P a g e
Code:
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
30 | P a g e
j=j+1
k=k+1
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
Experiment 13
Description: Program printing the N prime number till the upper limit.
Algorithm:
Take in the upper limit for the range and store it in a variable.
Let the first for loop range from 2 to the upper limit.
Initialize the count variable to 0.
Let the second for loop range from 2 to half of the number (excluding 1 and the number
itself).
Then find the number of divisors using the if statement and increment the count variable
each time.
If the number of divisors is lesser than or equal to 0, the number is prime.
Print the final result.
Exit.
31 | P a g e
Code:
r=int(input("Enter upper limit: "))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print (a)
Experiment 14
32 | P a g e
Code:
# Program
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
33 | P a g e