0% found this document useful (0 votes)
119 views

Python Programming Lab Programs

The document provides information about a Python Programming Laboratory course offered at NITTE MEENAKSHI INSTITUTE OF TECHNOLOGY. The course aims to teach core Python programming concepts and object-oriented programming. The laboratory manual contains 6 experiments covering topics like linear/binary search, stack implementation, file handling, and data wrangling using Pandas. Students will also complete a mini-project to demonstrate their skills in applying Python concepts.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

Python Programming Lab Programs

The document provides information about a Python Programming Laboratory course offered at NITTE MEENAKSHI INSTITUTE OF TECHNOLOGY. The course aims to teach core Python programming concepts and object-oriented programming. The laboratory manual contains 6 experiments covering topics like linear/binary search, stack implementation, file handling, and data wrangling using Pandas. Students will also complete a mini-project to demonstrate their skills in applying Python concepts.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

NITTE MEENAKSHI INSTITUTE OF TECHNOLOGY

(Autonomous Institution, Affiliated to VTU, Belgaum, Approved by AICTE & State Govt. of Karnataka)

Yelahanka, Bangalore – 560064

DEPARTMENT OF M.C.A.

Python Programming
Laboratory
22MCA207L
LAB MANUAL 2022-24

Lab Manual for Python Programming Laboratory-22MCA207L


Python Programming Laboratory
[As per Choice Based Credit System (CBCS) scheme]
SEMESTER –II
Subject Code 22MCA207L CIE Marks 50
Number of Hours/ Week 02 Hrs Laboratory SEE Marks 50
SEE Hours 03
CREDITS – 01
COURSE DESCRIPTION
This course is intended to provide students with the skills required to understand the basic
working of Python Programming. It demonstrates the Real-time Object-oriented programming
concepts with respect to handling database and Data Frames with panda’s library.
PREREQUISITES
 Students should know basics of Programming.
 Students should know C, C++, and Java Programming Concepts.
Course Objectives:
 To be able to introduce core programming basics and program design with functions
using Python programming language.
 To understand a range of Object-Oriented Programming, as well as in-depth data and
information processing techniques.
PART A - Laboratory Experiments
1 a. Implement a python program to search an element using linear search.
b. Implement a python program to search an element using binary search.
2 a. Implement a python program to insert an element into a sorted list.
b. Implement a python program to simulate stack.
3 Write a python program using object-oriented programming to demonstrate
a. encapsulation
b. overloading
c. inheritance.
4 a. Implement a Python Program for file operations.
b. Implement a python program to demonstrate data wrangling functions.
5 a. Implement a python program to Importing Datasets and demonstrate the basic operations
on them w.r.t Pandas.
b. Implement a Python program to demonstrate the working of DataFrames using
Pandas.
6 a. Implement a python program to demonstrate the following using NumPy: a) Array
manipulation, Searching, Sorting and splitting.
b. Broadcasting and Plotting NumPy arrays using matplotlib library.
PART B - MINI PROJECT
Develop a mini project using the python programming using the concepts learning during the
theory class.

Note:
1. In the examination each student should pick one program from Part-A,
2. A team of two or three students must develop the mini project. However during the
examination, each student must demonstrate the project individually.
3. The team must submit a brief project report (15-20 pages)

Lab Manual for Python Programming Laboratory-22MCA207L


1a .Implement a python program to search an element using linear search.
Program:
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = linear_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Output:

b. Implement a python program to search an element using binary search.


def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1

Lab Manual for Python Programming Laboratory-22MCA207L


alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = binary_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Output:

Lab Manual for Python Programming Laboratory-22MCA207L


2a. Implement a python program to insert an element into a sorted list.
Program:
import bisect
def insert(list_, n):
bisect.insort(list_, n)
return list_
list_ = ['a','b','c','d','e']
n = 'u'
print(insert(list_, n))

Output:

b. Implement a python program to simulate stack.


Program:
# Python program to
# demonstrate stack implementation
# using collections.deque

from collections import deque

stack = deque()

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack:')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
Lab Manual for Python Programming Laboratory-22MCA207L
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)
Output:

2b. Implementation using List:


#using list
stack = []

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop


# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)
Output:

Lab Manual for Python Programming Laboratory-22MCA207L


Lab Manual for Python Programming Laboratory-22MCA207L
3. Write a python program using object-oriented programming to
demonstrate encapsulation, overloading and inheritance.
Program to demonstrate Inheritance:
Python program to
# Demonstrate private members
# Creating a Base class
class Base:
def __init__(self):
self.a = "MCA"
self._c = "DEAPRTMENT"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

Output:

Program to demonstrate Operator Overloading:


# Python Program to perform addition
# of two complex numbers using binary
# + operator overloading.

Lab Manual for Python Programming Laboratory-22MCA207L


class complex:
def __init__(self, a, b):
self.a = a
self.b = b

# adding two objects


def __add__(self, other):
return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)

Output:

Lab Manual for Python Programming Laboratory-22MCA207L


4. Implement a Python Program for file operations: 1: open file in read
mode 2: open the file in write mode 3: append function 4: split function 5:
exit.

1. Program to open file in read mode:

# a file named "geek", will be opened with the reading mode.


file = open('file.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
# Python code to illustrate read() mode
file = open("file.txt", "r")
print (file.read())
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))

Output:
The interpreter will read the first five characters of stored data and return it as a string

2. To open a file in write mode:

# Python code to create a file


file = open('file.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

3. Append function:
# Python code to illustrate append() mode
file = open('geek.txt','a')
file.write("This will add this line")
file.close()

4. Split function:
# Python code to illustrate split() function
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Lab Manual for Python Programming Laboratory-22MCA207L


5. Closing of file:
file = open (“abc.txt”,”a”) file.write (“append the text”) file.close()

Note: file.txt has to be created separately with some input data

4b. data wrangling merging, concat,filtering and reshaping


# Import module
import pandas as pd

# Creating Dataframe
details = pd.DataFrame({
'ID': [101, 102, 103, 104, 105,
106, 107, 108, 109, 110],
'NAME': ['Jagroop', 'Praveen', 'Harjot',
'Pooja', 'Rahul', 'Nikita',
'Saurabh', 'Ayush', 'Dolly', "Mohit"],
'BRANCH': ['MCA', 'EEE', 'ISE', 'MECH', 'CSE',
'ECE', 'MBA', 'AERO', 'MCA', 'CIVIL']})

# Creating Dataframe
fees_status = pd.DataFrame(
{'ID': [101, 102, 103, 104, 105,
106, 107, 108, 109, 110],
'PENDING': ['5000', '250', 'NIL',
'9000', '15000', 'NIL',
'4500', '1800', '250', 'NIL']})

# Merging Dataframe
print(pd.merge(details, fees_status, on='ID'))
# Concatination
print (pd.concat([details, fees_status]))
#diaplay non duplicate value
df = pd.DataFrame(fees_status)

# Here df.duplicated() list duplicate Entries in ROllno.


# So that ~(NOT) is placed in order to get non duplicate values.
non_duplicate = df[~df.duplicated('PENDING')]

# printing non-duplicate values


print(non_duplicate)
#filtering
df_filtered = df.query('ID>105')

Lab Manual for Python Programming Laboratory-22MCA207L


print(df_filtered)
Output:

Lab Manual for Python Programming Laboratory-22MCA207L


5 a. Implement a python program to Importing Datasets and demonstrate the basic operations on
them w.r.t Pandas.

1. Importing Dataset:

import pandas as pd
df = pd.read_csv('csv.csv')
print(df.to_string())

CSV file:

2. Cleaning the Data


#display first and last 5 rows
import pandas as pd
df = pd.read_csv('csv.csv')
print(df)

Output:

Lab Manual for Python Programming Laboratory-22MCA207L


#display max rows
import pandas as pd

print(pd.options.display.max_rows)

Output:

Lab Manual for Python Programming Laboratory-22MCA207L


5B. Implement a Python program to demonstrate the working of
DataFrames using Pandas.

import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charles', 'David', 'Eric'],
'year': [2017, 2017, 2017, 2017, 2017],
'salary': [40000, 24000, 31000, 20000, 30000]}
data1 = pd.DataFrame({
Lab Manual for Python Programming Laboratory-22MCA207L
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5'],
'Marks_scored':[89,80,79,97,88]},

df = pd.DataFrame(data, index = ['Acme', 'Acme', 'Bilbao', 'Bilbao', 'Bilbao'])

print(df)

Output:

Filtering option:
1. df_filtered = df.query('salary>30000')
print(df_filtered)

Output:

2. df_filtered = df[(df.salary >= 30000) & (df.year == 2017)]


print(df_filtered)

Output:

Lab Manual for Python Programming Laboratory-22MCA207L


6a. Implement a python program to demonstrate the following using
NumPy: a) Array manipulation, Searching, Sorting and splitting
Program:
#6a lab program to implement array manipulation on numpy
import numpy as np
#cretaion of 2d array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
#cretaion of 3d array
arrr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arrr)
#searching with index
print('2nd element on 1st row: ', arr[0, 1])
print('Last element from 2nd dim: ', arr[1, -1])
#indexing of 3d array
print(arrr[0, 1, 2])
print(arrr[1, 1:4])
#slicing
print(arrr[1:5:2])
print(arrr[0:2, 1:4])
print(arrr[::2])
#sorting and searching
ar = np.array([9,2,1,5,3,10,33,12,56,78,13,8,6])
print(ar)
print(np.sort(ar))
x = np.searchsorted(ar, [2, 4, 6])
print(x)
#reshaping
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)
#splitting of array
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)

Lab Manual for Python Programming Laboratory-22MCA207L


Output:

6b) Broadcasting and Plotting NumPy arrays using matplotlib library.


Program:
#broadcasting and plotting of numpy arrays
import numpy as np
import matplotlib.pyplot as plt
# Computes x and y coordinates for
# points on sine and cosine curves
#trignometric broadcasting
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')

Lab Manual for Python Programming Laboratory-22MCA207L


plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()

Output:

Lab Manual for Python Programming Laboratory-22MCA207L

You might also like