4th Sem Python Manual Final
4th Sem Python Manual Final
LAB MANUAL
(2022-23)EVEN
21CSL46
PYTHON PROGRAMMING
LABORATORY
IV Semester
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Name: _____________________________________________
USN: ______________________________________________
Batch: _____________________________________________
21CSL46
PYTHON PROGRAMMING
LABORATORY
IV Semester
LAB MANUAL
Prepared By:
Prof. SHWETHA A B
Assistant Professor, Dept. of CSE
[email protected]
Prof. LAVANYA K
Assistant Professor, Dept. of CSE
[email protected]
VISION
To be a best institution imparting quality engineering education to deal with community needs
through learning and performance.
MISSION
To implement path breaking student centric education methods.
To augment talent, nurture teamwork to transform to develop individual as responsible citizen.
To educate the students and faculties about entrepreneurship to meet vibrant requirements of the
society.
Strengthen Industry-Institute Interaction for knowledge sharing.
VISION
MISSION
The program educational objectives of Bachelor of Engineering in Computer Science & Engineering
at Sapthagiri College of Engineering are broadly defined on following four counts.
III. Employability
Graduates will be advancing in their proficient skills to prepare them for improved growth in
varied career paths of Computer Science and Engineering and related fields.
PEO 1: Graduates will have the expertise in analyzing real time problems and providing
Appropriate solutions related to Computer Science & Engineering.
PEO 2: Graduates will have the knowledge of fundamental principles and innovative technologies to
succeed in higher studies, and research.
PEO 3: Graduates will continue to learn and to adapt technology developments combined with deep
awareness of ethical responsibilities in profession
The graduates of Computer Science and Engineering program at Sapthagiri College of engineering will
be able to attain the following at the time of graduation.
PSO 1: Apply the knowledge gained from Mathematics, Basic Computing, Basic Sciences and Social
Sciences in general and all computer science courses in particular to identify, formulate and solve real
life engineering problems.
PSO2: Identify the various analysis & design methodologies for facilitating development of high
quality system software products with focus on performance optimization.
PSO3: Apply modern technology to implement in the components and its system.
PROGRAM OUTCOMES:
Don’ts
Do not use mobile phone inside the lab.
Don’t do anything that can make the LAB dirty (like eating, throwing waste papers etc).
Do not carry any external devices without permission.
SCE, Dept of CSE 2022-23 5
PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.E
Don’t move the chairs of the LAB.
Don’t interchange any part of one computer with another.
Don’t leave the computers of the LAB turned on while leaving the LAB.
Do not install or download any software or modify or delete any system files on any lab
computers.
Do not damage, remove, or disconnect any labels, parts, cables, or equipment.
Don’t attempt to bypass the computer security system.
Do not read or modify other user’s file.
If you leave the lab, do not leave your personal belongings unattended.
We are not responsible for any theft.
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.
1
Datatypes: https://www.youtube.com/watch?v=gCCVsvgR2KU
Operators: https://www.youtube.com/watch?v=v5MR5JnKcZI
Flow Control: https://www.youtube.com/watch?v=PqFKRqpHrjw
For loop: https://www.youtube.com/watch?v=0ZvaDa8eT5s
While loop: https://www.youtube.com/watch?v=HZARImviDxg
Exceptions: https://www.youtube.com/watch?v=6SPDvPK38tw
Functions: https://www.youtube.com/watch?v=BVfCWuca9nw
Arguments: https://www.youtube.com/watch?v=ijXMGpoMkhQ
Return value: https://www.youtube.com/watch?v=nuNXiEDnM44
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
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
Strings: https://www.youtube.com/watch?v=lSItwlnF0eU
String functions: https://www.youtube.com/watch?v=9a3CxJyTq00
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.
Lists: https://www.youtube.com/watch?v=Eaz5e6M8tL4
4
List methods: https://www.youtube.com/watch?v=8-RDVWGktuI
Tuples: https://www.youtube.com/watch?v=bdS4dHIJGBc
Tuple operations: https://www.youtube.com/watch?v=TItKabcTTQ4
Dictionary: https://www.youtube.com/watch?v=4Q0pW8XBOkc
Dictionary methods: https://www.youtube.com/watch?v=oLeNHuORpNY
Aim: Demonstration of pattern recognition with and without using regular expressions
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
6 b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
Files: https://www.youtube.com/watch?v=vuyb7CxZgbU
https://www.youtube.com/watch?v=FqcjKewJTQ0
a) Write a python program to find the whether the given input is palindrome or not (for
8
both string and integer) using the concept of polymorphism and inheritance.
Overriding: https://www.youtube.com/watch?v=CcTzTuIsoFk
Aim: Demonstration of working with excel spreadsheets and web scraping
Excel: https://www.youtube.com/watch?v=nsKNPHJ9iPc
PDFs: https://www.youtube.com/watch?v=q70xzDG6nls
10 https://www.youtube.com/watch?v=JhQVD7Y1bsA
https://www.youtube.com/watch?v=FcrW-ESdY-A
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
Each experiment to be evaluated for conduction with observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments designed
by the faculty who is handling the laboratory session and is made known to students at the
beginning of the practical session.
Record should contain all the specified experiments in the syllabus and each experiment write-up
will be evaluated for 10 marks.
Total marks scored by the students are scaled downed to 30 marks (60% of maximum marks).
Weightage to be given for neatness and submission of record/write-up on time.
Department shall conduct 02 tests for 100 marks, the first test shall be conducted after the 8 th
week of the semester and the second test shall be conducted after the 14 th week of the semester.
In each test, test write-up, conduction of experiment, acceptable result, and procedural knowledge
will carry a weightage of 60% and the rest 40% for viva-voce.
The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
Rubrics suggested in Annexure-II of Regulation book
The average of 02 tests is scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and average marks of two tests is
the total CIE marks scored by the student.
Semester End Evaluation (SEE):
WEB PROGRAMMING
(Practical based)
Course Code 21CSL481 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 1:0:0:0 SEE Marks 50
Total Hours of Pedagogy 12T + 12P Total Marks 100
Credits 01 Exam Hours 02
Course Objectives:
CLO 1. Learn Web tool box and history of web browsers.
CLO 2. Learn HTML, XHTML tags with utilizations.
CLO 3. Know CSS with dynamic document utilizations.
CLO 4. Learn JavaScript with Element access in JavaScript.
CLO 5. Logically plan and develop web pages..
Teaching-Learning Process (General Instructions)
These are sample Strategies, which teachers can use to accelerate the attainment of the various course
outcomes.
1. Lecturer method (L) need not to be only a traditional lecture method, but alternative effective
teaching methods could be adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes critical
thinking.
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop design
thinking skills such as the ability to design, evaluate, generalize, and analyze information
rather than simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem with different circuits/logic and encourage
the students to come up with their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it helps
improve the students' understanding.
Module-1
Introduction to WEB Programming: Internet, WWW, Web Browsers, and Web Servers, URLs, MIME,
HTTP, Security, The Web Programmers Toolbox.
Aim: Introduce the Python fundamentals, data types, operators, flow control and exception handling in Python
a) Write a python program to find the best of two test average marks out of three test’s marks accepted from
the user.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Output:
Enter a value : 1234234
Not Palindrome
1 appears 1 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Program 2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
Output:
Enter a number : 5
fn(5) = 3
Enter a number : -1
Error in input
b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
Output:
Output:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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:
b) Write a Python program to find the string similarity between two given strings
Sample Output:
Original string:
Python Exercises
Python Exercises
Similarity between two said strings: 1.0
Sample Output:
Original string:
Python Exercises
Python Exercise
Similarity between two said strings: 0.967741935483871
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
Program 4
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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]
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]
b) Write a program to convert roman numbers in to integer values using dictionaries.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
Program 5
Aim: Demonstration of pattern recognition with and without using regular expressions
a) Write a function called is phone number () to recognize a pattern 415-555-4242 without using regular
expression and also write the code to recognize the same pattern using regular expression.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
Output:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
matches = email_regex.findall(line)
# Print any matches found
for match in matches:
print(match)
Output:
+918151894220
+829392938876
+918768456234
[email protected]
Program 6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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])
Output:
Enter the filename : example.txt
1 : this is phone number +918151894220
2 : no phone number here
3 : here we have one +829392938876
4 : we have an email [email protected] and a number +918768456234
5 : nothing of that sort here
6 : Better hope the life-inspector doesn't come around while you have your
7 : life in such a mess.
8 : You can create your own opportunities this week. Blackmail a senior executive.
9 : Be different: conform.
10 : Be cheerful while you are alive.
11 : -- Phathotep, 24th Century B.C.
12 : Q: How many journalists does it take to screw in a light bulb?
13 : A: Three. One to report it as an inspired government program to bring
14 : light to the people, one to report it as a diabolical government plot
15 : to deprive the poor of darkness, and one to win a Pulitzer prize for
16 : reporting that Electric Company hired a light bulb-assassin to break
17 : the bulb in the first place.
18 : Q: Why did the astrophysicist order three hamburgers?
19 : A: Because he was hungry.
20 : Q: Why haven't you graduated yet?
Enter a word : the
The word the appears 7 times in the file
b) Write a python program to create a ZIP file of a particular folder which contains several files inside it.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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:
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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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 : "))
print("Updated Salary", self.salary)
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
Output:
Employee Details
Name : Sameer
ID : A123
Dept : CSE
Salary : 85750
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class PaliStr:
def __init__(self):
self.isPali = False
return self.isPali
class PaliInt(PaliStr):
def __init__(self):
self.isPali = False
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:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import os
from bs4 import BeautifulSoup
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...
b) Demonstrate python program to read the data from the spreadsheet and write the data in to the
spreadsheet
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "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 = 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"]
wb.close()
Output:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
num = int(input("Enter page number you want combine from multiple documents "))
pdf1 = open('birds.pdf', 'rb')
pdf2 = open('birdspic.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('output.pdf', 'wb') as output:
pdf_writer.write(output)
Output:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
JSON File
{
"coord": {
"lon": -73.99,
"lat": 40.73
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"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: