EAST WESTINSTITUTE OFTECHNOLOGY
# 63 Off Magadi Main Road, Vishwaneedam Post, Bangalore-91
(Affiliated to VTU, Belagavi, Approved by AICTE, New Delhi & Recognized by Govt. of Karnataka)
Department of Artificial Intelligence and Data Science
Engineering
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:
m1 = int(input("Enter marks for test1 : ")) m2 =
int(input("Enter marks for test2 : ")) m3 =
int(input("Enter marks for test3 : ")) if m1 <= m2
and m1 <= m3:
avgMarks = (m2+m3)/2 elif m2
<= m1 and m2 <= m3:
avgMarks = (m1+m3)/2 elif m3
<= m1 and m2 <= m2:
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:
val = int(input("Enter a value : "))
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:
print(str(i),"appears", str_val.count(str(i)), "times")
OUTPUT 1b:
Department of AD, EWIT Bangalore Page 4
Python Programming Laboratory (21CSL46)
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:
Department of AD, EWIT Bangalore Page 5
Python Programming Laboratory (21CSL46)
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
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:
Department of AD, EWIT Bangalore Page 6
Python Programming Laboratory (21CSL46)
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 2b:
Department of AD, EWIT Bangalore Page 7
Python Programming Laboratory (21CSL46)
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:
sentence = input("Enter a sentence : ")
wordList = sentence.split(" ")
print("This sentence has", len(wordList), "words")
digCnt = upCnt = loCnt = 0
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 3a:
Department of AD, EWIT Bangalore Page 8
Python Programming Laboratory (21CSL46)
Program 3b: Write a Python program to find the string similarity between two given strings.
CODE 3b:
str1 = input("Enter String 1 \n")
str2 = input("Enter String 2 \n")
if len(str2) < len(str1):
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("Similarity between two said strings:")
print(matchCnt/long)
OUTPUT 3b:
Department of AD, EWIT Bangalore Page 9
Python Programming Laboratory (21CSL46)
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
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
Department of AD, EWIT Bangalore Page 10
Python Programming Laboratory (21CSL46)
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 k in range(10):
my_list.append(random.randint(0, 999))
Department of AD, EWIT Bangalore Page 11
Python Programming Laboratory (21CSL46)
print("\nUnsorted List")
print(my_list)
print("Sorting using Merge Sort")
merge_sort(my_list)
print(my_list)
OUTPUT 4a:
Department of AD, EWIT Bangalore Page 12
Python Programming Laboratory (21CSL46)
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]]
for numeral in romanBack:
leftVal = roman_dict[numeral]
if leftVal < rightVal:
value -=
leftVal else:
value += leftVal
rightVal = leftVal
return value
romanStr = input("Enter a Roman Number : ")
print(roman2Dec(romanStr))
OUTPUT 4b:
Department of AD, EWIT Bangalore Page 13
Python Programming Laboratory (21CSL46)
PROGRAM 5
Aim: Demonstration of pattern recognition with and without using regular expression.
Program 5a: 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.
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() ==
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
Department of AD, EWIT Bangalore Page 14
Python Programming Laboratory (21CSL46)
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")
print("Using Regular Expression")
if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
OUTPUT: 5a
Department of AD, EWIT Bangalore Page 15
Python Programming Laboratory (21CSL46)
Program 5b: Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected])
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,}')
# 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
for match in matches:
print(match)
matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
Department of AD, EWIT Bangalore Page 16
Python Programming Laboratory (21CSL46)
OUTPUT 5b:
Department of AD, EWIT Bangalore Page 17
Python Programming Laboratory (21CSL46)
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
fname = input("Enter the filename : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
lineList = infile.readlines()
for i in range(20):
print(i+1, ":", lineList[i])
word = input("Enter a word : ")
cnt = 0
for line in lineList:
cnt += line.count(word)
print("The word", word, "appears", cnt, "times in the file")
Department of AD, EWIT Bangalore Page 18
Python Programming Laboratory (21CSL46)
OUTPUT 6a:
Department of AD, EWIT Bangalore Page 19
Python Programming Laboratory (21CSL46)
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
dirName = input("Enter Directory name that you want to backup : ")
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Department of AD, EWIT Bangalore Page 20
Python Programming Laboratory (21CSL46)
OUTPUT 6b:
Department of AD, EWIT Bangalore Page 21
Python Programming Laboratory (21CSL46)
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:
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):
Department of AD, EWIT Bangalore Page 22
Python Programming Laboratory (21CSL46)
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)
Department of AD, EWIT Bangalore Page 23
Python Programming Laboratory (21CSL46)
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:
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 : ")
Department of AD, EWIT Bangalore Page 24
Python Programming Laboratory (21CSL46)
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 : "))
print("Updated Salary", self.salary)
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
OUTPUT 7b:
Department of AD, EWIT Bangalore Page 25
Python Programming Laboratory (21CSL46)
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:
def init (self):
self.isPali = False
def chkPalindrome(self, myStr):
if myStr == myStr[::-1]:
self.isPali = True
else:
self.isPali = False
return self.isPali
class PaliInt(PaliStr):
def init (self):
self.isPali = False
def chkPalindrome(self, val):
temp = val
rev = 0
while temp != 0:
Department of AD, EWIT Bangalore Page 26
Python Programming Laboratory (21CSL46)
dig = temp % 10
rev = (rev*10) + dig
temp = temp //10
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")
Department of AD, EWIT Bangalore Page 27
Python Programming Laboratory (21CSL46)
else:
Department of AD, EWIT Bangalore Page 28
Python Programming Laboratory (21CSL46)
print("Given integer is not a Palindrome")
OUTPUT 8a:
Department of AD, EWIT Bangalore Page 29
Python Programming Laboratory (21CSL46)
PROGRAM 9
Aim: Demonstration working with excel spreadsheets and webscrapping.
Program 9a: Write a python program to download all XKCD comics.
CODE 9a:
import requests
import os
from bs4 import BeautifulSoup
# Set the URL of the first XKCD comic
url = 'https://xkcd.com/1/'
# Create a folder to store the comics
if not os.path.exists('xkcd_comics'):
os.makedirs('xkcd_comics')
# Loop through all the comics
while True:
# Download the page content
res = requests.get(url)
res.raise_for_status()
# Parse the page content using BeautifulSoup
soup = BeautifulSoup(res.text, 'html.parser')
Department of AD, EWIT Bangalore Page 30
Python Programming Laboratory (21CSL46)
# Find the URL of the comic image
comic_elem = soup.select('#comic img')
if comic_elem == []:
print('Could not find comic image.')
else:
comic_url = 'https:' + comic_elem[0].get('src')
# Download the comic image
print(f'Downloading {comic_url}...')
res = requests.get(comic_url)
res.raise_for_status()
# Save the comic image to the xkcd_comics folder
image_file = open(os.path.join('xkcd_comics', os.path.basename(comic_url)), 'wb')
for chunk in res.iter_content(100000):
image_file.write(chunk)
image_file.close()
# Get the URL of the previous comic
prev_link = soup.select('a[rel="prev"]')[0]
if not prev_link:
break
url = 'https://xkcd.com' + prev_link.get('href')
print('All comics downloaded.')
Department of AD, EWIT Bangalore Page 31
Python Programming Laboratory (21CSL46)
OUTPUT 9a:
Program 9b: Demonstrate python program to read the data from the spreadsheet and write the
data into the spreadsheet.
CODE 9b:
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
Department of AD, EWIT Bangalore Page 32
Python Programming Laboratory (21CSL46)
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")
lang = ["Kannada", "Telugu", "Tamil"]
state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Language"
sheet.cell(row = 1, column = 3).value = "Code"
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")
Department of AD, EWIT Bangalore Page 33
Python Programming Laboratory (21CSL46)
sheet = wb["Capital"]
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Capital"
sheet.cell(row = 1, column = 3).value = "Code"
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")
srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding capital for code", srchCode, "is", sheet.cell(row = i, column =
2).value)
Department of AD, EWIT Bangalore Page 34
Python Programming Laboratory (21CSL46)
sheet = wb["Language"]
srchCode = input("Enter state code for finding language ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding language for code", srchCode, "is",
sheet.cell(row =i ,column = 2).value)
wb.close()
OUTPUT 9b:
Department of AD, EWIT Bangalore Page 35
Python Programming Laboratory (21CSL46)
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:
from PyPDF2 import PdfWriter, PdfReader
num = int(input("Enter page number you want combine from multiple documents
")) pdf1 = open('pysyll.pdf', 'rb')
pdf2 = open('ossyll.pdf', 'rb')
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)
with open('outputs.pdf', 'wb') as output:
pdf_writer.write(output)
print("New pdf 'outputs.pdf' is generated")
OUTPUT 10a:
Department of AD, EWIT Bangalore Page 36
Python Programming Laboratory (21CSL46)
Program 10b: Write a python program to fetch current weather data from JSON files.
CODE 10b:
import json
# Load the JSON data from file
with open('weather_data.json') as f:
data = json.load(f)
# Extract the required weather data
current_temp = data['main']
['temp'] humidity = data['main']
['humidity']
weather_desc = data['weather'][0]['description']
# Display the weather data
print(f"Current temperature: {current_temp}°C")
print(f"Humidity: {humidity}%")
print(f"Weather description: {weather_desc}")
OUTPUT 10b:
Department of AD, EWIT Bangalore Page 37