Python Programming Laboratory (21csl46) Complete Manual
Python Programming Laboratory (21csl46) Complete Manual
VTU Syllabus
PART A – List of problems for which student should develop program and
execute in the Laboratory
Aim 1: Introduce the Python fundamentals, data types, operators, flow control and exception handling
in Python
1 a) Write a python program to find the best of two test average marks out of three test’s marks accepted from the
user.
print("The average of two best test marks out of three test marks = ",avg)
1 b) Develop a Python program to check whether a given number is palindrome or not and also count the
number of occurrences of each digit in the input number.
if r == 0:
c0+=1
elif r == 1:
c1+=1
elif r == 2:
c2+=1
elif r == 3:
c3+=1
elif r == 4:
c4+=1
elif r == 5:
c5+=1
elif r == 6:
c6+=1
elif r == 7:
c7+=1
elif r == 8:
c8+=1
elif r == 9:
c9+=1
if rev==num:
print("The Number {0} is palindrome ".format(num))
else:
print("The Number {0} is not palindrome ".format(num))
print("The occurrence of 0 is {0}, 1 is {1}, 2 is {2}, 3 is {3}, 4 is {4}, 5 is {5}, 6 is {6}, 7 is {7}, 8 is {8}, 9 is
{9}".format(c0,c1,c2,c3,c4,c5,c6,c7,c8,c9))
2 a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value for N
(where N >0) as input and pass this value to the function. Display suitable error message if the condition
for input value is not followed.
n = int(input("Enter the value of n: ")) # read the number of terms of the Fibonacci series
Fibo(n) # invoke the function F to generate the Fibonacci series of n terms
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
while dec != 0: # till decimal equivalent value of the Ocatl nu (dec) is >0 do the following
temp = 0
temp = dec % 16 # get Hex value of least significant digit of Decimal number
if temp < 10: # if the Hex value is single digit number
result = str(temp) + result # convert it into string and accumulate in Result
else:
result = chr(temp + 87) + result # else if the Hex value is more than 9 then get the equivalent Hex digit
dec = dec // 16 # get the next Hex value and repeat
return result # return the Hex Decimal equivalent of the Decimal number
if result:
print("The Hexa Decimal equivalent of {0} is {1}".format(y, result))
3 a) Write a Python program that accepts a sentence and find the number of words, digits, uppercase
letters and lowercase letters.
3 b) Write a Python program to find the string similarity between two given strings
j=0
similarity = (sim/len(xx)) # compute similarity = (similarity between strings) / length of longer string
4 a) Write a python program to implement insertion sort and merge sort using lists
def InsertionSort(lst):
i=0
while i<len(lst): #Till i less than the length of the list repeat
small = lst[i]
for j in range(i+1,len(lst)): # Find the smallest element of the list
nxt =lst[j]
if small>nxt:
small = lst[j]
index = lst.index(small) # index is the index of the smallest element
if i==index : # if element is at its correct position then do nothing
pass
else:
lst.remove(small) # Else move the smallest to its correct position
lst.insert(i,small)
i=i+1
return lst
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2 # Create sub_array2 ← A[start..mid]
sub_array1 = arr[:mid] # and sub_array2 ← A[mid+1..end]
sub_array2 = arr[mid:]
i=j=k=0 # Initial values for pointers to keep track of where we are in each array
while i < len(sub_array1): # When all elements are traversed in either arr1 or arr2,
arr[k] = sub_array1[i] # pick up the remaining elements and put in sorted array
i += 1
k += 1
while j < len(sub_array2):
arr[k] = sub_array2[j]
j += 1
k += 1
return arr
def roman_to_int(s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val
Aim 5: Demonstration of pattern recognition with and without using regular expressions
5 a) Write a function called isphonenumber () to recognize a pattern 415-555-4242 without using regular
expression and also write the code to recognize the same pattern using regular expression.
def isphonenumber(x):
l = len(x)
if l!=12:
return 0
else:
for i in range(0,l):
if i==0 or i==1 or i==2 :
if x[i].isdigit() == False:
return 0
if i==4 or i==5 or i==6 :
if x[i].isdigit() == False:
return 0
if i==8 or i==9 or i==10 :
if x[i].isdigit() == False:
return 0
if i==3 or i==7:
if x[i] != '-':
return 0
return 1
def REisphonenumber(x):
import re
pno = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = pno.search(x)
if mo == None:
return 0
else:
return mo.group()
5 b) Develop a python program that could search the text in a file for phone numbers (+919900889977)
and email addresses ([email protected])
import re
try:
file = open("data.txt")
for line in file:
line = line.strip()
match = re.findall(r"(\d{10})", line)
if(len(match)>0):
print(match)
emails = re.findall("[0-9a-zA-z]+@[0-9a-zA-z]+\.[0-9a-zA-z]+", line)
if(len(emails) > 0):
print(emails)
except FileNotFoundError as e:
print(e)
6 a) Write a python program to accept a file name from the user and perform the following operations
1. Display the first N line of the file
2. Find the frequency of occurrence of the word accepted from the user in the file
with open(inputFile, 'r') as filedata: # Opening the given file in read-only mode
linesList= filedata.readlines() # Read the file lines using readlines()
print("The following are the first",N,"lines of a text file:")
for textline in (linesList[:N]): # Traverse in the list of lines to retrieve the first N lines of a file
print(textline, end ='') # Printing the first N lines of the file line by line.
6 b) Write a python program to create a ZIP file of a particular folder containing several files inside it.
zipObj.write(filePath, basename(filePath))
7 a) By using the concept of inheritance write a python program to find the area of triangle, circle and
rectangle.
class Shape:
area,radius,length,breadth,a,b,c=0,0,0,0,0,0,0
def init (self, r):
self.radius = r
def init (self, l,b):
self.length = l
self.breadth = b
def init (self, a,b,c):
self.a = a
self.b = b
self.c = c
class Circle(Shape):
def init (self,r):
super(). init (r,0,0)
def area(self,r):
print("The area of circle is ",3.14*r*r)
class Rectangle(Shape):
def init (self,l,b):
super(). init (0,l,b)
def area(self,l,b):
print("The area of rectangle is ",l*b)
class Triangle(Shape):
def init (self,a,b,c):
super(). init (a,b,c)
def area(self,a,b,c):
s = (a+b+c)/2
import math
print("The area of triangle is ",math.sqrt(s*(s-a)*(s-b)*(s-c)))
c = Circle(r)
c.area(r)
elif ch==2:
l = int(input("Enter length of rectangle"))
b = int(input("Enter breadth of rectangle"))
r = Rectangle(l,b)
r.area(l,b)
elif ch==3:
a = int(input("Enter length of side a of triangle"))
b = int(input("Enter length of side b of triangle"))
c = int(input("Enter length of side c of triangle"))
t = Triangle(5,6,7)
t.area(5,6,7)
else:
print("Invalid choice")
7 b) Write a python program by creating a class called Employee to store the details of Name,
Employee_ID, Department and Salary, and implement a method to update salary of employees belonging
to a given department.
class Employee:
def init (self,name,eid,dept,sal):
self.name = name
self.eid = eid
self.dept = dept
self.sal = sal
def salUpdate(self,eid,dept,updsal):
self.sal = updsal
8. Write a python program to find the whether the given input is palindrome or not (for both string and
integer) using the concept of polymorphism and inheritance.
class strPalindrome:
def init (self):
self.word=""
self.ll=""
def check(self,s):
self.word = list(s)
ll=self.word.copy()
self.word.reverse()
if (ll==self.word):
print("\nIt is Palindrome")
else:
print("\nIt is Not Palindrome")
class noPalindrome(strPalindrome):
def init (self):
super(). init
def check(self,no):
super().check(str(no))
print("Done")
9 b) Demonstrate python program to read the data from the spreadsheet and write the data in to the
spreadsheet
print("\nValue of first column") # printing the value of first column Loop will print all values of first column
for i in range(1, row + 1):
cell_obj = sheet_obj.cell(row = i, column = 1)
print(cell_obj.value)
print("\nValue of first row") # printing the value of first column Loop will print all values of first row
for i in range(1, column + 1):
cell_obj = sheet_obj.cell(row = 2, column = i)
print(cell_obj.value, end = " ")
# import openpyxl module # Call a Workbook() function of openpyxl to create a new blank Workbook object
wb = openpyxl.Workbook()
sheet = wb.active # Get workbook active sheet from the active attribute
# Cell objects also have row, column and coordinate attributes that provide location information for the cell.
# Note: The first row or column integer is 1, not 0. Cell object is created by using sheet object's cell() method.
c1 = sheet.cell(row = 1, column = 1)
# Once have a Worksheet object, one can access a cell object by its name. A2 means column = 1 & row = 2.
c3 = sheet['A2']
c3.value = "Welcome"
# Anytime you modify the Workbook object or its sheets and cells, the spreadsheet file will not be saved until
Aim 10: Demonstration of working with PDF, word and JSON files
10 b) Write a python program to fetch current weather data from the JSON file