Python Final Lab Manual
Python Final Lab Manual
Laboratory Manual
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
(Accredited by NBA)
2021 Scheme
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
(Accredited by NBA)
Couse
Course Outcome
Index
Laboratory Programs
PART-A
List of problems for which student should develop program and execute in the Laboratory
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.
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.
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.
b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
3. a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings.
4. a) Write a python program to implement insertion sort and merge sort using lists.
b) Write a program to convert roman numbers in to integer values using dictionaries.
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.
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com).
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.
b) Write a python program to create a ZIP file of a particular folder which contains several files
inside it.
7. a) By using the concept of inheritance write a python program to find the area of triangle, circle
and rectangle.
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.
8. a) 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.
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering
9. a) Write a python program to download the all XKCD comics b) Demonstrate python program
to read the data from the spreadsheet and write the data in to the spreadsheet
10. a) Write a python program to combine select pages from many PDFs.
b) Write a python program to fetch current weather data from the JSON file
PART-B
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.
m1 = int(input("Enter marks for test1 : "))
m2 = int(input("Enter marks for test2 : "))
m3 = int(input("Enter marks for test3 : "))
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.
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
Output:
Enter a value : 121
Palindrome
1 appears 2 times
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering
2 appears 1 times
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.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")# Call the Fibonacci function and display the result or error message
result = F(n)
if result is not None:
print(f"The numbers till N are: {result}")
Output:
Enter a number : 5
fn(5) = 3
2 b). Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
def bin2Dec(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 2**i
i += 1
return dec
def oct2Hex(val):
rev=val[::-1]
dec = 0
i=0
for dig in rev:
dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
list.append(dec%16)
dec = dec // 16
nl=[]
for elem in list[::-1]:
if elem <= 9:
nl.append(str(elem))
else:
nl.append(chr(ord('A') + (elem -10)))
hex = "".join(nl)
return hex
num1 = input("Enter a binary number : ")
print(bin2Dec(num1))
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
Output:
Enter a binary number : 10111001
185
Enter a octal number : 675
1BD
3 a). Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
Output:
Enter a sentence : Rama went to Devaraja market to pick 2 kgs of vegetable
This sentence has 11 words
This sentence has 1 digits 2 upper case letters 42 lower case letters
3 b) Write a Python program to find the string similarity between two given
strings Sample Output: Sample Output:
Original String: Original String:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: Similarity between two said strings:
1.0 0.967741935483871
import difflib
def string_similarity(str1, str2):
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering
# Initializing strings
test_string1 = 'Python Exerises'
test_string2 = ' Python Exerises''
4 a). Write a python program to implement insertion sort and merge sort
using lists import random
import random
def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
lst[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
lst[k] = right_half[j]
j += 1
k += 1
return lst
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
my_list = []
for i in range(10):
my_list.append(random.randint(0, 999))
print("\nUnsorted List")
print(my_list)
print("Sorting using Insertion Sort")
insertion_sort(my_list)
print(my_list)
my_list = []
for i in range(10):
my_list.append(random.randint(0, 999))
print("\nUnsorted List")
print(my_list)
print("Sorting using Merge Sort")
merge_sort(my_list)
print(my_list)
Output:
Unsorted List
[932, 111, 226, 685, 543, 589, 918, 539, 294, 717]
Sorting using Insertion Sort
[111, 226, 294, 539, 543, 589, 685, 717, 918, 932]
Unsorted List
[613, 176, 828, 265, 65, 326, 359, 919, 514, 868]
Sorting using Merge Sort
[65, 176, 265, 326, 359, 514, 613, 828, 868, 919]
def roman2Dec(romStr):
roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# Analyze string backwards
romanBack = list(romStr)[::-1]
value = 0
# To keep track of order
rightVal = roman_dict[romanBack[0]]
for numeral in romanBack:
leftVal = roman_dict[numeral]
# Check for subtraction
if leftVal < rightVal:
value -= leftVal
else:
value += leftVal
rightVal = leftVal
return value
romanStr = input("Enter a Roman Number : ")
print(roman2Dec(romanStr))
Output:
Enter a Roman Number : XVII
17
Enter a Roman Number : MLXVI
1066
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.
import re
def isphonenumber(numStr):
if len(numStr) != 12:
return False
for i in range(len(numStr)):
if i==3 or i==7:
if numStr[i] != "-":
return False
else:
if numStr[i].isdigit() == False:
return False
return True
def chkphonenumber(numStr):
ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')
if ph_no_pattern.match(numStr):
return True
else:
return False
ph_num = input("Enter a phone number : ")
print("Without using Regular Expression")
if isphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
5 b). Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
import re
# Define the regular expression for phone numbers
phone_regex = re.compile(r'\+\d{12}')
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
# Open the file for reading
with open('example.txt', 'r') as f:
# Loop through each line in the file
for line in f:
# Search for phone numbers in the line
matches = phone_regex.findall(line)
# Print any matches found
matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
Output:
+918151894220
+829392938876
+918768456234
prakash81.82@gmail.in
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
import os.path
import sys
if not os.path.isfile(fname):
sys.exit(0)
lineList = infile.readlines()
for i in range(20):
cnt = 0
cnt += line.count(word)
Output:
6 : Better hope the life-inspector doesn't come around while you have your
8 : You can create your own opportunities this week. Blackmail a senior executive.
9 : Be different: conform.
15 : to deprive the poor of darkness, and one to win a Pulitzer prize for
6 b). Write a python program to create a zip of a particular folder which contains
import os
from zipfile import ZipFile
7. a). By using the concept of inheritance write a python program to find the area of triangle,
circle and rectangle.
import math
class Shape:
def __init__(self):
self.area = 0
self.name = ""
def showArea(self):
print("The area of the", self.name, "is", self.area, "units")
class Circle(Shape):
def __init__(self,radius):
self.area = 0
self.name = "Circle"
self.radius = radius
def calcArea(self):
self.area = math.pi * self.radius * self.radius
class Rectangle(Shape):
def __init__(self,length,breadth):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth
def calcArea(self):
self.area = self.length * self.breadth
class Triangle(Shape):
def __init__(self,base,height):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height
def calcArea(self):
self.area = self.base * self.height / 2
c1 = Circle(5)
c1.calcArea()
c1.showArea()
r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()
t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()
Output:
the area of the Circle is 113.09733552923255 units
the area of the Rectangle is 210 units
the area of the Triangle is 91.0 units
7. b). 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):
self.name = ""
self.empId = ""
self.dept = ""
self.salary = 0
def getEmpDetails(self):
self.name = input("Enter Employee name : ")
self.empId = input("Enter Employee ID : ")
self.dept = input("Enter Employee Dept : ")
self.salary = int(input("Enter Employee Salary : "))
def showEmpDetails(self):
print("Employee Details")
print("Name : ", self.name)
print("ID : ", self.empId)
print("Dept : ", self.dept)
print("Salary : ", self.salary)
def updtSalary(self):
self.salary = int(input("Enter new Salary : "))
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
Output:-
Enter Employee name :Ramu
Enter Employee ID :986
Enter Employee Dept :cse
Enter Employee Salary :120000
Employee Details
Name : Ramu
ID : 986
Dept : cse
Enter new Salary : 13000
Updated Salary 13000
8. a) 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 PaliStr:
def __init__(self):
self.isPali = False
return self.isPali
Python Programming Laboratory(21CSL46) Semester IV
Department of Computer Science & Engineering
class PaliInt(PaliStr):
def __init__(self):
self.isPali = False
if val == rev:
self.isPali = True
else:
self.isPali = False
return self.isPali
st = input("Enter a string : ")
stObj = PaliStr()
if stObj.chkPalindrome(st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")
val = int(input("Enter a integer : "))
intObj = PaliInt()
if intObj.chkPalindrome(val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")
Output:
Enter a string : madam
Given string is a Palindrome
Enter a integer : 121
Given integer is a Palindrome
print("Done")
Output:
9 b). Demonstrate python program to read the data from the spreadsheet and write the data in to
the spreadsheet
sh1.cell(row=5,column=1,value='MT21CS135')
sh1['A5'].fill=PatternFill("solid",fgColor="71FF33")
sh1.cell(row=5,column=2,value='sathvik')
sh1['B5'].fill=PatternFill("solid",fgColor="71FF33")
sh1.cell(row=5,column=3,value='20')
sh1['C5'].fill=PatternFill("solid",fgColor="71FF33")
sh1.cell(row=5,column=4,value='16')
sh1['D5'].fill=PatternFill("solid",fgColor="71FF33")
wb.save('newsheet.xlsx') # creates new xlsx file with old and new data in a new
filename
Output:
10 a). Write a python program to combine select pages from many PDFs
num = int(input("Enter page number you want combine from multiple documents "))
Output:
file1.pdf file2.pdf
Outputfile.pdf
10 b). Write a python program to fetch current weather data from the JSON file
api_key = "980fc61e5f43515a2ec709c871aa6b70"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = input("Enter city name : ")
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
Output: