21CSL46 Python Programming Lab Sambhram
21CSL46 Python Programming Lab Sambhram
COMPILED BY
RAJENDRA M
REVIEWED BY
DR. LATHA P.H
HOD, DEPT OF IS&E
SYLLABUS
1
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
2
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
3
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
4
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
5
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
1A) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
print("Average of best two test marks out of three test’s marks is", avgMarks);
Output
Enter marks for test1 : 45
Enter marks for test2 : 39
Enter marks for test3 : 48
Average of best two test marks out of three test’s marks is 46.5
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
6
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
Not Palindrome
1 appears 1 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
2B) Develop a python program to convert binary to decimal, octal to hexadecimal using
7
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
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
8
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
3A)Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.
for ch in sentence:
if '0' <= ch <= '9':
digCnt += 1
elif 'A' <= ch <= 'Z':
upCnt += 1
elif 'a' <= ch <= 'z':
loCnt += 1
print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case
letters")
Output
9
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
3B) Write a Python program to find the string similarity between two given strings.
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
Output
Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0
Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings:
0.9375
10
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
4A) Write a python program to implement insertion sort and merge sort using lists.
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
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]
11
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
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]
12
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
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
Output
13
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
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
14
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
5B) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
import re
matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
15
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
+918151894220
+829392938876
+918768456234
prakash81.82@gmail.in
6A) Write a python program to accept a file name from the user and perform the
following operations
import os.path
import sys
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
lineList = infile.readlines()
for i in range(20):
print(i+1, ":", lineList[i])
16
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
17
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
import os
import sys
import pathlib
import zipfile
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Output
18
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
7A) 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)
19
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
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 78.53981633974483 units
The area of the Rectangle is 20 units
The area of the Triangle is 6.0 units
7B) 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)
20
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
def updtSalary(self):
self.salary = int(input("Enter new Salary : "))
print("Updated Salary", self.salary)
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
Output
Employee Details
Name : Sameer
ID : A123
Dept : CSE
Salary : 85750
8A) 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
class PaliInt(PaliStr):
def __init__(self):
self.isPali = False
21
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
if val == rev:
self.isPali = True
else:
self.isPali = False
return self.isPali
stObj = PaliStr()
if stObj.chkPalindrome(st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")
intObj = PaliInt()
if intObj.chkPalindrome(val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")
Output
22
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
import requests
import os
from bs4 import BeautifulSoup
23
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
Downloading https://imgs.xkcd.com/comics/barrel_cropped_(1).jpg...
Downloading https://imgs.xkcd.com/comics/radians_are_cursed.png...
Downloading https://imgs.xkcd.com/comics/presents_for_biologists.png...
Downloading https://imgs.xkcd.com/comics/launch_window.png...
Downloading https://imgs.xkcd.com/comics/obituary_editor.png...
Downloading https://imgs.xkcd.com/comics/fanservice.png...
Downloading https://imgs.xkcd.com/comics/hand_dryers.png...
9B) Demonstrate python program to read the data from the spreadsheet and write the
data in to the spreadsheet
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")
24
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = lang[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("demo.xlsx")
sheet = wb["Capital"]
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = capital[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("demo.xlsx")
sheet = wb["Language"]
25
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
wb.close()
Output
10A) Write a python program to combine select pages from many PDFs
num = int(input("Enter page number you want combine from multiple documents "))
pdf_writer = PdfWriter()
pdf1_reader = PdfReader(pdf1)
page = pdf1_reader.pages[num - 1]
pdf_writer.add_page(page)
pdf2_reader = PdfReader(pdf2)
page = pdf2_reader.pages[num - 1]
pdf_writer.add_page(page)
26
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
Output
This program allows you to extract specific pages from two PDF files, “birds.pdf” and
“birdspic.pdf,” by entering the page numbers as user input. Once you input the desired page
numbers, the program fetches those pages from both PDF files and combines them into a new
file called “output.pdf.” This way, you can easily compile the desired pages from multiple
PDF files into one document for your convenience.
birdsDownload
birdspicDownload
outputDownload
10B) Write a python program to fetch current weather data from the JSON file
import json
27
Department of IS&E SaIT
21CSL46 Python Programming Laboratory
],
"base": "stations",
"main": {
"temp": 15.45,
"feels_like": 12.74,
"temp_min": 14.44,
"temp_max": 16.11,
"pressure": 1017,
"humidity": 64
},
"visibility": 10000,
"wind": {
"speed": 4.63,
"deg": 180
},
"clouds": {
"all": 1
},
"dt": 1617979985,
"sys": {
"type": 1,
"id": 5141,
"country": "US",
"sunrise": 1617951158,
"sunset": 1618000213
},
"timezone": -14400,
"id": 5128581,
"name": "New York",
"cod": 200
}
Output
Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky
28
Department of IS&E SaIT