Python - Lab - Manual 2
Python - Lab - Manual 2
Python
Laboratory MANUAL
(21CSL46)
IV Semester B.E
Prepared by,
Dr. Suresh M B Ms. Smitha
K.S
Prof & Head Asst. Prof
Dept. of ISE Dept. of ISE
PROGRAM 1
Aim: Introduce a python fundamentals, data types, operators, flow control and exception
handling in Python.
Program 1a: Write a python program to find the best of two test average marks out of three test's
marks accepted from the user.
CODE 1a:
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is", avgMarks)
OUTPUT 1a:
Python Programming Laboratory (21CSL46)
Program 1b: Develope a python program to check whether a given number is palindrome or
not and also count the number of occurences of each digit in input number.
CODE 1b:
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
OUTPUT 1b:
PROGRAM 2
Aim: Demonstrating creation of functions, passing parameters and return values.
Program 2a: 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.
CODE 2a:
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")
OUTPUT 2a:
Program 2b: Develop a python program to convert binary to decimal, octal to hexadecimal
using functions.
CODE 2b:
def bin2Dec(val):
rev=val[::-1]
dec = 0
i=0
i += 1
return dec
def oct2Hex(val):
rev=val[::-1]
dec = 0
i=0
i += 1
list=[]
while dec != 0:
list.append(dec%16)
dec = dec // 16
nl=[]
if elem <= 9:
nl.append(str(elem))
else:
hex = "".join(nl)
return hex
print(bin2Dec(num1))
print(oct2Hex(num2))
OUTPUT 2b:
PROGRAM 3
Aim: Demonstration of manipulation of strings using string methods.
Program 3a: Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters and lowercase letters.
CODE 3a:
for ch in sentence:
'9':
digCnt += 1
upCnt += 1
'z': loCnt += 1
print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt, "lower case
letters")
OUTPUT 3a:
Program 3b: Write a Python program to find the string similarity between two given strings.
CODE 3b:
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print(matchCnt/long)
OUTPUT 3b:
PROGRAM 4
Aim: Discuss different collections like list, tuple and dictionary.
Program 4a: Write a program to implement insertion sort and merge sort using lists.
CODE 4a:
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
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1
lst[k] = left_half[i]
i += 1
k += 1
lst[k] = right_half[j]
j += 1
k += 1
return lst
def insertion_sort(arr):
key = arr[i]
j=i-1
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)
insertion_sort(my_list)
print(my_list)
my_list = []
for k in range(10):
my_list.append(random.randint(0, 999))
print("\nUnsorted List")
print(my_list)
merge_sort(my_list)
print(my_list)
OUTPUT 4a:
Program 4b: 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.
CODE 4b:
def roman2Dec(romStr):
roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
romanBack = list(romStr)[::-1]
value = 0
rightVal = roman_dict[romanBack[0]]
leftVal = roman_dict[numeral]
value -=
leftVal else:
value += leftVal
rightVal = leftVal
return value
print(roman2Dec(romanStr))
OUTPUT 4b:
PROGRAM 5
Aim: Demonstration of pattern recognition with and without using regular expression.
CODE 5a:
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() ==
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
if isphonenumber(ph_num):
else:
if chkphonenumber(ph_num):
else:
OUTPUT: 5a
Program 5b: Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
CODE 5b:
import re
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,}')
for line in f:
matches = phone_regex.findall(line)
print(match)
matches = email_regex.findall(line)
print(match)
OUTPUT 5b:
PROGRAM 6
Aim: Demonstration of reading, writing and organising files.
Program 6a: Write a python program to accept a file name from the user and perform the
following operations. Display the first N line of the file. Find the frequency of occurrence of the
word accepted from the user in the file.
CODE 6a:
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 6a:
Program 6b: Write a python program to create a ZIP file of a particular folder which
contains several files in it.
CODE 6b :
import os
import sys
import pathlib
import zipfile
if not os.path.isdir(dirName):
sys.exit(0)
curDirectory = pathlib.Path(dirName)
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
else:
OUTPUT 6b:
PROGRAM 7
Aim: Demonstration of the concept of classes, methods, objects and Inheritance.
Program 7a: By using the concept of inheritance write a python program to find area of
triangle, circle and rectangle.
CODE 7a:
import math
class Shape:
self.area = 0
self.name = ""
def showArea(self):
class Circle(Shape):
self.area = 0
self.name = "Circle"
self.radius = radius
def calcArea(self):
class Rectangle(Shape):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth
def calcArea(self):
class Triangle(Shape):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height
def calcArea(self):
c1 = Circle(5)
c1.calcArea()
c1.showArea()
r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()
t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()
OUTPUT 7a:
Program 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 given department.
CODE 7b:
class Employee:
self.name = ""
self.empId = ""
self.dept = ""
self.salary = 0
def getEmpDetails(self):
def showEmpDetails(self):
print("Employee Details")
print("Salary : ",
self.salary)
def updtSalary(self):
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
OUTPUT 7b:
PROGRAM 8
Aim: Demonstration of classes and methods with polymorphism and overriding.
Program 8a: Write a program to find the whether the given input is palindrome or not (for both
string and integer) using the concept of polymorphism and inheritance.
CODE 8a:
class PaliStr:
self.isPali = False
if myStr == myStr[::-1]:
self.isPali = True
else:
self.isPali = False
return self.isPali
class PaliInt(PaliStr):
self.isPali = False
temp = val
rev = 0
while temp != 0:
dig = temp % 10
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:
intObj = PaliInt()
if intObj.chkPalindrome(val):
else:
OUTPUT 8a:
PROGRAM 9
Aim: Demonstration working with excel spreadsheets and webscrapping.
CODE 9a:
import requests
import os
url = 'https://xkcd.com/1/'
if not os.path.exists('xkcd_comics'):
os.makedirs('xkcd_comics')
while True:
res = requests.get(url)
res.raise_for_status()
if comic_elem == []:
else:
print(f'Downloading {comic_url}...')
res = requests.get(comic_url)
res.raise_for_status()
image_file.write(chunk)
image_file.close()
prev_link = soup.select('a[rel="prev"]')[0]
if not prev_link:
break
OUTPUT 9a:
Program 9b: Demonstrate python program to read the data from the spreadsheet and write the
data into the spreadsheet.
CODE 9b:
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")
ft = Font(bold=True)
cell.font = ft
for i in range(2,5):
wb.save("demo.xlsx")
sheet = wb["Capital"]
ft = Font(bold=True)
cell.font = ft
for i in range(2,5):
wb.save("demo.xlsx")
for i in range(2,5):
if data == srchCode:
sheet = wb["Language"]
for i in range(2,5):
if data == srchCode:
wb.close()
OUTPUT 9b:
PROGRAM 10
Aim: Demonstration of working with PDF, word and JSON files.
Program 10a: Write a python program to combine select pages from many PDFs
CODE 10a:
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)
pdf_writer.write(output)
OUTPUT 10a:
Program 10b: Write a python program to fetch current weather data from JSON files.
CODE 10b:
import json
with open('weather_data.json') as f:
data = json.load(f)
current_temp = data['main']
['humidity']
weather_desc = data['weather'][0]['description']
print(f"Humidity: {humidity}%")
OUTPUT 10b: