100% found this document useful (1 vote)
3K views

Faculty Python Lab Manual

This document outlines the vision, mission, program educational objectives, program outcomes, course outcomes, experiments, tools and reference materials for a Python programming laboratory course at ABES Engineering College. The course aims to teach students Python programming fundamentals and applications through a series of experiments. Requirements include Python 3.6.4, Anaconda distribution, and reference is made to documentation, websites and books on Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views

Faculty Python Lab Manual

This document outlines the vision, mission, program educational objectives, program outcomes, course outcomes, experiments, tools and reference materials for a Python programming laboratory course at ABES Engineering College. The course aims to teach students Python programming fundamentals and applications through a series of experiments. Requirements include Python 3.6.4, Anaconda distribution, and reference is made to documentation, websites and books on Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

ABES Engineering College, Ghaziabad

Affiliated to Dr. A.P.J AKTU, Lucknow

Department of Information Technology

Laboratory Manual

Session 2019-20(Even Semester)


Name : Mr. Jitendra Kumar Chauhan/Ms.
Shelley Gupta
Subject Name : Python Language Programming Lab
Subject Code : KCS 453
Semester : B. Tech. IT IV

(Faculty Copy)
1|Page
Department of Information Technology

Vision

The Department of Information Technology endeavors to be recognized globally for outstanding


education and research leading to well qualified engineers, who are innovative, entrepreneurial
and successful in advanced fields of IT to cater the ever changing industrial demands and social
needs.

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)

PO-1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO-2: Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO-3: Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
PO-4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO-5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO-6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO-7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO-8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO-9: Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
PO-10: Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
PO-11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

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

Program Specific Outcomes (PSOs)

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.

Course Outcomes PSO1 PSO2 PSO3 PSO4


CO1 1 1 1 2
CO2 1 1 2 1
CO3 2 1 2 1
CO4 2 1 1 2
CO5 1 1 1 1

5|Page
Course Objectives (COs)
CO 1 To read and write simple Python programs. K1, K2

CO 2 To develop Python programs with conditionals and loops. K2, K4

CO 3 To define Python functions and to use Python data structures –- lists, tuples, K3
dictionaries

CO 4 To do input/output with files in Python K2

CO 5 To do searching ,sorting and merging in Python K2, K4

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.

(Faculty signature) Dr. (Prof.) Amit Sinha


HOD (IT)

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

 John M. Sewart, “Python for Scientist”, Cambridge Universities Press.


 Reema Thareja, “Python Programming” Oxford Higher Education.
 Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in
Python” Pearson
 Mrak Litz, “ Learning Python”,O’ Reilly
 Mark Pilgrim, “Dive into Python”, Apress
 James L. Young, “Python made Simple and Practical ”, Kindle Edition (paperback)
 Y. Daniel Liang “Introduction to Programming using Python” Pearson

(Faculty signature) Dr. (Prof.) Amit Sinha


HOD (IT)

ABES Engineering College, Ghaziabad

7|Page
List of Experiments

1. S.No. Experiment Name Prescribed by L_COs Page


University No.
/Faculty

1 To write a python program that takes in command line University 1 9


arguments as input and print the number of arguments.
2 To write a python program to perform Matrix University 1,2 10
Multiplication.
3 To write a python program to compute the GCD of University 1 13
two numbers.

4 To write a python program to find the most frequent University 2,3 15


words in a text file.

5 T To write a python program find the square root of a University 3 17


number (Newton’s method).

6 To write a python program exponentiation (power of a University 3 19


number).

7 To write a python program find the maximum of a list University 3 20


of numbers.

8 T To write a python program linear search. University 2 3,5 2 22

9 To write a python program Binary search. University 3,5 24

10 To write a python program selection sort. University 3,5 26

11 To write a python program Insertion sort. University 3,5 28

12 To write a python program merge sort. University 3,5 30


13 To write a python program first n prime numbers. University 3 32

14 To write a python program simulate bouncing ball in University 4 33


Pygame.

(Sign of Faculty) Dr. (Prof.) Amit Sinha


HOD (IT)

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

Objective: To write a python program to perform Matrix Multiplication.


Description:
Given two matrix the task is that we will have to create a program to multiply two matrices in
python.
9|Page
Examples:
Input: X = [[1, 7, 3],
[3, 5, 6],
[6, 8, 9]]
Y = [[1, 1, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

Output: [55, 65, 49, 5]


[57, 68, 72, 12]
[90, 107, 111, 21]

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

Objective: To write a python program to compute the GCD of two numbers.

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 = [];

#Opens a file in read mode


file = open("data.txt", "r")

#Gets each line till end of file is reached


for line in file:
#Splits each line into words
string = line.lower().replace(',','').replace('.','').split(" ");
#Adding all words generated in previous step into words
for s in string:
words.append(s);

#Determine the most repeated word in a file


for i in range(0, len(words)):
count = 1;
#Count each word in the file and store it in variable count
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;

#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.

input: initial x, func(x), derivFunc(x)


Output: Root of Func()

1. Compute values of func(x) and derivFunc(x) for given initial x


2. Compute h: h = func(x) / derivFunc(x)
3. While h is greater than allowed error ε
1. h = func(x) / derivFunc(x)
2. x = x – h

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

Objective : To write a python program exponentiation (power of a number)

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:

Enter any base


Enter Power
power = 1
for i in range(1, exponent + 1):
Output = power * number
Print number, exponent and output

Flow Chart:

Code:
Base = int(input(" Please Enter any Positive Base : "))
Power = int(input(" Please Enter Power Value : "))
output= 1

for i in range(1, Power + 1):


output = output * Base

print("The Result of {0} Power {1} = {2}".format(Base, Power, output))

19 | P a g e
Experiment 7

Objective : To write a python program find the maximum of a list of numbers.

Description
Input : list1 = [10, 20, 4]
Output : 20

Input : list2 = [20, 10, 20, 4, 100]


Output : 100

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]

# sorting the list


list1.sort()

# printing the last element


print("Largest element is:", list1[-1])
3. Using max() method
# Python program to find largest
# number in a list

# 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

Objective. To write a python program linear search.

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

while pos < len(dlist) and not found:


if dlist[pos] == item:
found = True
else:
pos = pos + 1

return found, pos

print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))

Experiment 9

Objective. To write a python program Binary search.

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:

Compare x with the middle element.


If x matches with middle element, we return the mid index.
Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
Else (x is smaller) recur for the left half.

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

Objective 10. To write a python program selection sort.

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:

1. Create a function selectionSort that takes a list as argument.


25 | P a g e
2. Inside the function create a loop with a loop variable i that counts from 0 to the length of
the list – 1.
3. Create a variable smallest with initial value i.
4. Create an inner loop with a loop variable j that counts from i + 1 up to the length of the
list – 1.

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

Objective. To write a python program Insertion sort.

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

while position>0 and nlist[position-1]>currentvalue:


nlist[position]=nlist[position-1]
position = position-1

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

Objective. To write a python program merge sort.

Description: "Merge sort (also commonly spelled mergesort) is an O (n log n) comparison-based


sorting algorithm. Most implementations produce a stable sort, which means that the
implementation preserves the input order of equal elements in the sorted output."

Algorithm: Conceptually, a merge sort works as follows:

 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

while i < len(lefthalf):


nlist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)

nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)

Experiment 13

Objective 13. To write a python program to print first N prime numbers

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

Objective 14. To write a python program simulate bouncing ball in Pygame.

Algorithm - Bouncing ball


 Start the program
 Set screen size and background color.
 Set speed of moving ball.
 Create a graphical window using set_mode()
 Set caption
 Load the ball image and create a rectangle area covering the image
 Use blit() method to copy the pixel color of the ball to the screen
 Set background color of screen and use flip () method to make all images visible.
 Move the ball in specified speed.
 If ball hits the edges of the screen reverse the direction.
 Create an infinite loop and Repeat steps 9 and 10 until user quits the program
 Stop the program

32 | P a g e
Code:
# Program

import sys, pygame


pygame.init()

size = width, height = 700, 300


speed = [1, 1]
background = 255, 255, 255

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

You might also like