PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.
SAPTHAGIRI COLLEGE OF ENGINEERING
#14/5, Chikkasandra, Hesaraghatta Main Road, Bengaluru.
LAB MANUAL
(2022-23)EVEN
21CSL46
PYTHON PROGRAMMING
LABORATORY
IV Semester
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Name: _____________________________________________
USN: ______________________________________________
Batch: _____________________________________________
SCE, Dept of CSE 2022-23 1
PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.E
VISVESVARAYA TECHNOLOGICAL UNIVERSITY Jnana
Sangama, Belagavi, Karnataka – 590018
21CSL46
PYTHON PROGRAMMING
LABORATORY
IV Semester
LAB MANUAL
Prepared By:
Prof. SHWETHA A B
Assistant Professor, Dept. of CSE
shwetha_ab@[Link]
Prof. LAVANYA K
Assistant Professor, Dept. of CSE
lavanyak@[Link]
SCE, Dept of CSE 2022-23 2
PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.E
VISION AND MISSION OF INSTITUTE
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 AND MISSION OF DEPARTMENT
VISION
To be a potential quality source of expert computer engineers, addressing the requirements of
industry and civic demands at large.
MISSION
Enable learning in cutting-edge technologies adopting innovative methods.
To enhance ability, cultivate collaboration to bring change in building students approach towards
society.
Make available platform for harnessing entrepreneurial and leadership qualities.
Partner continuously with industry to design and implement practical syllabus .
PROGRAM EDUCATIONAL OBJECTIVES (PEO)
The program educational objectives of Bachelor of Engineering in Computer Science & Engineering
at Sapthagiri College of Engineering are broadly defined on following four counts.
I. Technical expertise and problem solving
Graduates will have the expertise in analyzing real time problems and providing appropriate
solutions related to Computer Science & Engineering.
II. Innovation and Research
Graduates will have the knowledge of fundamental principles and innovative technologies to
succeed in higher studies and research.
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.
SCE, Dept of CSE 2022-23 3
PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.E
IV. Professional ethics
Graduates will continue to learn and to adapt technology developments combined with deep
awareness of ethical responsibilities in profession.
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
PROGRAM SPECIFIC OUTCOMES (PSO)
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:
Engineering Graduates will be able to:
PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
PO2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, societal, and environmental considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
SCE, Dept of CSE 2022-23 4
PYTHON PROGRAMMING LABORATORY – 21CSL46 IV Semester /B.E
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
DO’S AND DON’TS
Do’s
Do wear ID card and follow dress code. Do log off the computers when you finish.
Be on time to LAB sessions.
Do ask for assistance if you need help.
Do keep your voice low when speaking to others in the LAB.
Do make suggestions as to how we can improve the LAB.
In case of any hardware related problem, ask LAB in charge for solution.
If you are the last one leaving the LAB, make sure that the staff in charge of the LAB is informed
to close the LAB
Do keep the LAB as clean as possible.
Do prepare for lab programs before entering the lab
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.
SCE, Dept of CSE 2022-23 6
IV Semester
PYTHON PROGRAMMING LABORATORY
Course Code 21CSL46 CIE Marks 50
Teaching Hours/Weeks (L: T: P: S) 0: 0: 2: 0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 01 Exam Hours 03
Course Objectives:
CLO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications
CLO 2. Using Python programming language to develop programs for solving real-world problems
CLO 3. Implement the Object-Oriented Programming concepts in Python.
CLO 4. Appraise the need for working with various documents like Excel, PDF, Word and Others
CLO 5. Demonstrate regular expression using python programming
Note: two hours tutorial is suggested for each laboratory sessions.
Prerequisite
Students should be familiarized about Python installation and setting Python environment
Usage of IDLE or IDE like PyCharm should be introduced
Python Installation: [Link]
PyCharm Installation: [Link]
Sl. No. PART A – List of problems for which student should develop program and execute in
the Laboratory
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.
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: [Link]
Operators: [Link]
Flow Control: [Link]
For loop: [Link]
While loop: [Link]
Exceptions: [Link]
Aim: Demonstrating creation of functions, passing parameters and return values
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
2
functions.
Functions: [Link]
Arguments: [Link]
Return value: [Link]
Aim: Demonstration of manipulation of strings using string methods
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: [Link]
String functions: [Link]
Aim: Discuss different collections like list, tuple and dictionary
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: [Link]
4
List methods: [Link]
Tuples: [Link]
Tuple operations: [Link]
Dictionary: [Link]
Dictionary methods: [Link]
Aim: Demonstration of pattern recognition with and without using regular expressions
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.
5
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@[Link])
Regular expressions: [Link]
Aim: Demonstration of reading, writing and organizing files.
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: [Link]
[Link]
File organization: [Link]
7 Aim: Demonstration of the concepts of classes, methods, objects and inheritance
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.
OOP’s concepts: [Link]
Inheritance: [Link]
Aim: Demonstration of classes and methods with polymorphism and overriding
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: [Link]
Aim: Demonstration of working with excel spreadsheets and web scraping
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
9
Web scraping: [Link]
Excel: [Link]
Aim: Demonstration of working with PDF, word and JSON files
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
PDFs: [Link]
10 [Link]
[Link]
Word files: [Link]
JSON files: [Link]
Python (Full Course): [Link]
For the above experiments the following pedagogy can be considered. Problem based
Pedagogy
learning, Active learning, MOOC, Chalk &Talk
PART B – Practical Based Learning
A problem statement for each batch is to be generated in consultation with the co-examiner and student
should develop an algorithm, program and execute the program for the given problem with appropriate
outputs.
Course Outcomes:
CO 1. Demonstrate proficiency in handling of loops and creation of functions.
CO 2. Identify the methods to create and manipulate lists, tuples and dictionaries.
CO 3. Discover the commonly used operations involving regular expressions and file system.
CO 4. Interpret the concepts of Object-Oriented Programming as used in Python.
CO 5. Determine the need for scraping websites and working with PDF, JSON and other file formats.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student
shall be deemed to have satisfied the academic requirements and earned the credits allotted to each
course. The student has to secure not less than 35% (18 Marks out of 50) in the semester-end
examination (SEE). The student has to secure 40% of sum of the maximum marks of CIE and SEE to
qualify in the course.
Continuous Internal Evaluation (CIE):
CIE marks for the practical course is 50 Marks.
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):
SEE marks for the practical course is 50 Marks.
SEE shall be conducted jointly by the two examiners of the same institute, examiners are
appointed by the University
All laboratory experiments are to be included for practical examination.
(Rubrics) Breakup of marks and the instructions printed on the cover page of the answer
script to be strictly adhered to by the examiners. OR based on the course requirement
evaluation rubrics shall be decided jointly by examiners.
Students can pick one question (experiment) from the questions lot prepared by the internal
/external examiners jointly.
Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly
by examiners.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure
and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for
100 marks and scored marks shall be scaled down to 50 marks (however, based on course
type, rubrics shall be decided by the examiners)
Students can pick one experiment from the questions lot of PART A with equal choice to all the
students in a batch. For PART B examiners should frame a question for each batch, student should
develop an algorithm, program, execute and demonstrate the results with appropriate output for
the given problem.
Weightage of marks for PART A is 80% and for PART B is 20%. General rubrics suggested to be
followed for part A and part B.
Change of experiment is allowed only once and Marks allotted to the procedure part to be
made zero (Not allowed for Part B).
The duration of SEE is 03 hours
Rubrics suggested in Annexure-II of Regulation book
Textbooks:
1. Al Sweigart, “Automate the Boring Stuff with Python”,1stEdition, No Starch Press, 2015.
(Available under CC-BY-NC-SA license at [Link]
2. Reema Thareja “Python Programming Using Problem Solving Approach” Oxford University
Press.
3. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”,
2nd Edition, Green Tea Press, 2015. (Available under CC-BY-NC license at
[Link]
IV Semester
WEB PROGRAMMING
(Practical based)
Course Code 21CSL481 CIE Marks 50
Teaching Hours/Week (L:T:P: S) [Link] 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.
Textbook 1: Chapter 1(1.1 to 1.9)
Teaching-Learning Process Chalk and board, Active Learning, practical based learning
Module-2
HTML and XHTML: Origins of HTML and XHTML, Basic syntax, Standard XHTML document structure,
Basic text markup, Images, Hypertext Links, Lists, Tables. Forms,
Frames in HTML and XHTML, Syntactic differences between HTML and XHTML.
Textbook 1: Chapter 2(2.1 to 2.10)
Teaching-Learning Process Chalk and board, Active Learning, Demonstration, presentation,
problem solving
Module-3
CSS: Introduction, Levels of style sheets, Style specification formats, Selector forms, Property value
forms, Font properties, List properties, Color, Alignment of text, Background images, tags.
Textbook 1: Chapter 3(3.1 to 3.12)
Teaching-Learning Process Chalk and board, Demonstration, problem solving
Module-4
Program 1
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 -*-
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:
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 -*-
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:
Enter a value : 1234234
Not Palindrome
1 appears 1 times
2 appears 2 times
3 appears 2 times
4 appears 2 times
Program 2
Aim: Demonstrating creation of functions, passing parameters and return values
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.
#!/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)
num = int(input("Enter a number : "))
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:
[Link](dec%16)
dec = dec // 16
nl=[]
for elem in list[::-1]:
if elem <= 9:
[Link](str(elem))
else:
[Link](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
Program 3
Aim: Demonstration of manipulation of strings using string methods
a) Write a Python program that accepts a sentence and find the number of words, digits, uppercase letters
and lowercase letters.
Output:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
sentence = input("Enter a sentence : ")
wordList = [Link](" ")
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:
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
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 -*-
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:
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
Aim: Discuss different collections like list, tuple and dictionary
a) Write a python program to implement insertion sort and merge sort using lists
#!/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
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([Link](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([Link](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 = [Link](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")
print("Using Regular Expression")
if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
Output:
Enter a phone number : 444-654-5656
Without using Regular Expression
Valid phone number
Using Regular Expression
Valid phone number
Enter a phone number : 45A4-444-878
Without using Regular Expression
Invalid phone number
Using Regular Expression
Invalid phone number
b) Develop a python program that could search the text in a file for phone numbers (+919900889977) and
email addresses (sample@[Link])
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
# Define the regular expression for phone numbers
phone_regex = [Link](r'\+\d{12}')
email_regex = [Link](r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
# Open the file for reading
with open('[Link]', '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)
Output:
+918151894220
+829392938876
+918768456234
prakash81.82@[Link]
Program 6
Aim: Demonstration of reading, writing and organizing files.
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import [Link]
import sys
fname = input("Enter the filename : ")
if not [Link](fname):
print("File", fname, "doesn't exists")
[Link](0)
infile = open(fname, "r")
lineList = [Link]()
for i in range(20):
print(i+1, ":", lineList[i])
word = input("Enter a word : ")
cnt = 0
for line in lineList:
cnt += [Link](word)
print("The word", word, "appears", cnt, "times in the file")
Output:
Enter the filename : [Link]
1 : this is phone number +918151894220
2 : no phone number here
3 : here we have one +829392938876
4 : we have an email prakash81.82@[Link] 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
dirName = input("Enter Directory name that you want to backup : ")
if not [Link](dirName):
print("Directory", dirName, "doesn't exists")
[Link](0)
curDirectory = [Link](dirName)
with [Link]("[Link]", mode="w") as archive:
for file_path in [Link]("*"):
[Link](file_path, arcname=file_path.relative_to(curDirectory))
if [Link]("[Link]"):
print("Archive", "[Link]", "created successfully")
else:
print("Error in creating zip archive")
Output:
Enter Directory name that you want to backup : zipDemo
Archive [Link] created successfully
Program 7
Aim: Demonstration of the concepts of classes, methods, objects and inheritance
a) By using the concept of inheritance write a python program to find the area of triangle, circle and
rectangle.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
class Shape:
def __init__(self):
[Link] = 0
[Link] = ""
def showArea(self):
print("The area of the", [Link], "is", [Link], "units")
class Circle(Shape):
def __init__(self,radius):
[Link] = 0
[Link] = "Circle"
[Link] = radius
def calcArea(self):
[Link] = [Link] * [Link] * [Link]
class Rectangle(Shape):
def __init__(self,length,breadth):
[Link] = 0
[Link] = "Rectangle"
[Link] = length
[Link] = breadth
def calcArea(self):
[Link] = [Link] * [Link]
class Triangle(Shape):
def __init__(self,base,height):
[Link] = 0
[Link] = "Triangle"
[Link] = base
[Link] = height
def calcArea(self):
[Link] = [Link] * [Link] / 2
c1 = Circle(5)
[Link]()
[Link]()
r1 = Rectangle(5, 4)
[Link]()
[Link]()
t1 = Triangle(3, 4)
[Link]()
[Link]()
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
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):
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = 0
def getEmpDetails(self):
[Link] = input("Enter Employee name : ")
[Link] = input("Enter Employee ID : ")
[Link] = input("Enter Employee Dept : ")
[Link] = int(input("Enter Employee Salary : "))
def showEmpDetails(self):
print("Employee Details")
print("Name : ", [Link])
print("ID : ", [Link])
print("Dept : ", [Link])
print("Salary : ", [Link])
def updtSalary(self):
[Link] = int(input("Enter new Salary : "))
print("Updated Salary", [Link])
e1 = Employee()
[Link]()
[Link]()
[Link]()
Output:
Enter Employee name : Sameer
Enter Employee ID : A123
Enter Employee Dept : CSE
Enter Employee Salary : 85750
Employee Details
Name : Sameer
ID : A123
Dept : CSE
Salary : 85750
Enter new Salary : 88800
Updated Salary 88800
Program 8
Aim: Demonstration of classes and methods with polymorphism and overriding
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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class PaliStr:
def __init__(self):
[Link] = False
def chkPalindrome(self, myStr):
if myStr == myStr[::-1]:
[Link] = True
else:
[Link] = False
return [Link]
class PaliInt(PaliStr):
def __init__(self):
[Link] = False
def chkPalindrome(self, val):
temp = val
rev = 0
while temp != 0:
dig = temp % 10
rev = (rev*10) + dig
temp = temp //10
if val == rev:
[Link] = True
else:
[Link] = False
return [Link]
st = input("Enter a string : ")
stObj = PaliStr()
if [Link](st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")
val = int(input("Enter a integer : "))
intObj = PaliInt()
if [Link](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 : 567587
Given integer is not a Palindrome
Enter a string : INDIA
Given string is not a Palindrome
Enter a integer : 6789876
Given integer is a Palindrome
Program 9
Aim: Demonstration of working with excel spreadsheets and web scraping
a) Write a python program to download the all XKCD comics
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import os
from bs4 import BeautifulSoup
# Set the URL of the first XKCD comic
url = '[Link]
# Create a folder to store the comics
if not [Link]('xkcd_comics'):
[Link]('xkcd_comics')
# Loop through all the comics
while True:
# Download the page content
res = [Link](url)
res.raise_for_status()
# Parse the page content using BeautifulSoup
soup = BeautifulSoup([Link], '[Link]')
# Find the URL of the comic image
comic_elem = [Link]('#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 = [Link](comic_url)
res.raise_for_status()
# Save the comic image to the xkcd_comics folder
image_file = open([Link]('xkcd_comics', [Link](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 = [Link]('a[rel="prev"]')[0]
if not prev_link:
break
url = '[Link] + prev_link.get('href')
print('All comics downloaded.')
Output:
Downloading [Link]
Downloading [Link]
Downloading [Link]
Downloading [Link]
Downloading [Link]
Downloading [Link]
Downloading [Link]
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 -*-
from openpyxl import Workbook
from [Link] import Font
wb = Workbook()
sheet = [Link]
[Link] = "Language"
wb.create_sheet(title = "Capital")
lang = ["Kannada", "Telugu", "Tamil"]
state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']
[Link](row = 1, column = 1).value = "State"
[Link](row = 1, column = 2).value = "Language"
[Link](row = 1, column = 3).value = "Code"
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
[Link] = ft
for i in range(2,5):
[Link](row = i, column = 1).value = state[i-2]
[Link](row = i, column = 2).value = lang[i-2]
[Link](row = i, column = 3).value = code[i-2]
[Link]("[Link]")
sheet = wb["Capital"]
[Link](row = 1, column = 1).value = "State"
[Link](row = 1, column = 2).value = "Capital"
[Link](row = 1, column = 3).value = "Code"
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
[Link] = ft
for i in range(2,5):
[Link](row = i, column = 1).value = state[i-2]
[Link](row = i, column = 2).value = capital[i-2]
[Link](row = i, column = 3).value = code[i-2]
[Link]("[Link]")
srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
data = [Link](row = i, column = 3).value
if data == srchCode:
print("Corresponding capital for code", srchCode, "is", [Link](row = i, column = 2).value)
sheet = wb["Language"]
srchCode = input("Enter state code for finding language ")
for i in range(2,5):
data = [Link](row = i, column = 3).value
if data == srchCode:
print("Corresponding language for code", srchCode, "is", [Link](row = i, column = 2).value)
[Link]()
Output:
Enter state code for finding capital KA
Corresponding capital for code KA is Bengaluru
Enter state code for finding language TS
Corresponding language for code TS is Telugu
Program 10
Aim: Demonstration of working with PDF, word and JSON files
a) Write a python program to combine select pages from many PDFs
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyPDF2 import PdfWriter, PdfReader
num = int(input("Enter page number you want combine from multiple documents "))
pdf1 = open('[Link]', 'rb')
pdf2 = open('[Link]', '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('[Link]', 'wb') as output:
pdf_writer.write(output)
Output:
Enter page number you want combine from multiple documents 3
b) Write a python program to fetch current weather data from the JSON file
Python File
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
# Load the JSON data from file
with open('weather_data.json') as f:
data = [Link](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}")
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:
Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky