Python Programming Manual-21CSL46
Python Programming Manual-21CSL46
IV SEMESTER
PYTHON PROGRAMMING LABORATORY LAB MANUAL
[21CSL46]
Compiled By:
VISION
To emerge as a centre for achieving academic excellence, by producing competent professionals
to meet the global challenges in the field of Information science and Technology.
MISSION
M1:To prepare the students as competent professionals to meet the advancements in the
industry and academia by imparting quality technical education.
M2:To enrich the technical ability of students to face the world with confidence, commitment
and teamwork
.
M3: To inculcate and practice strong techno-ethical values to serve the society.
PEO3: To engage in research and development leading to new innovations and products.
PSO3: Demonstrate the knowledge towards the domain specific initiatives of Information
Science and Engineering.
Program Outcomes (POs):
Information Science and Engineering Graduates will be able to:
PROGRAM -1
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.
PROGRAM -2
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 functions.
PROGRAM -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.
PROGRAM -4
a) Write a python program to implement insertion sort and merge sort using lists
b) Write a program to convert Roman numbers into integer values using dictionaries.
PROGRAM -5
b) Develop a Python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
PROGRAM -6
a) Write a python program to accept a file name from the user and perform the following
operations
2. Find the frequency of occurrence of the word accepted by the user in the file
b) Write a Python program to create a ZIP file of a particular folder that contains several files
inside it.
PROGRAM -7
a) By using the concept of inheritance write a python program to find the area of a 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 the salary of
employees belonging to a given department.
PROGRAM -8
a) Write a Python program to find whether the given input is palindrome or not (for both string
and integer) using the concept of polymorphism and inheritance.
PROGRAM -9
b) Demonstrate a python program to read the data from the spreadsheet and write the data into
the spreadsheet
PROGRAM -10
b) Write a python program to fetch current weather data from the JSON file
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.
Lesson plan
Python Programming Laboratory 21CSL46
Pre-requisites:
Knowledge about any programming language.
Learning 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 4. Appraise the need for working with various documents like Excel, PDF, Word
and Others
Course Outcomes:
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 CO1 TB1
1
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.
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 CO1 TB1
2
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
functions.
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, CO2 TB1
3
uppercase letters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings
Aim: Discuss different collections like list, tuple and dictionary
4 a) Write a python program to implement insertion sort and merge sort using lists CO2 TB1
b) Write a program to convert roman numbers in to integer values using dictionaries.
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
5 using regular expression and also write the code to recognize the same pattern using CO3 TB1
regular expression.
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
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
6 1. Display the first N line of the file CO3 TB1
2. Find the frequency of occurrence of the word accepted from the user in the file
b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
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. TB3
7 CO4
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.
Aim: Demonstration of classes and methods with polymorphism and overriding
8 a) Write a python program to find the whether the given input is palindrome or not (for CO4 TB3
both string and integer) using the concept of polymorphism and inheritance.
Aim: Demonstration of working with excel spreadsheets and web scraping
a) Write a python program to download the all XKCD comics TB1
9 CO5
b) Demonstrate python program to read the data from the spreadsheet and write the data
in to the spreadsheet
Aim: Demonstration of working with PDF, word and JSON files
10 a) Write a python program to combine select pages from many PDFs CO5 TB1
b) Write a python program to fetch current weather data from the JSON file
Text Books
E V R T E V R T
PROGRAM -1
1a) Write a Python program to find the best of two test average marks out of
three test marks accepted by the user.
avgMarks = (m2+m3)/2
avgMarks = (m1+m3)/2
avgMarks = (m1+m2)/2
print("Average of best two test marks out of three test’s marks is", avgMarks);
OUTPUT
Average of best two test marks out of three test’s marks is 46.5
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:
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
PROGRAM -2
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
def binary_to_decimal(binary):
decimal = 0
power = 0
while binary != 0:
last_digit = binary % 10
decimal += last_digit * (2 ** power)
binary //= 10
power += 1
return decimal
def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal != 0:
last_digit = octal % 10
decimal += last_digit * (8 ** power)
octal //= 10
power += 1
hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal != 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16
return hexadecimal
PROGRAM -3
3a) Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters, and lowercase letters.
def analyze_sentence(sentence):
word_count = len(sentence.split())
digit_count = 0
uppercase_count = 0
lowercase_count = 0
OUTPUT:
This sentence has 1 digits 2 upper case letters 42 lower case letters
3b) Write a Python program to find the string similarity between two given
strings.
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
4a) Write a python program to implement insertion sort and merge sort using
lists.
import random
def merge_sort(rec):
if len(rec) > 1:
mid = len(rec) // 2
left_half = rec[:mid]
right_half = rec[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
rec[k] = left_half[i]
i += 1
k += 1
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)
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)
merge_sort(my_list)
print(my_list)
OUTPUT:
Unsorted List
[932, 111, 226, 685, 543, 589, 918, 539, 294, 717]
[111, 226, 294, 539, 543, 589, 685, 717, 918, 932]
Unsorted List
[613, 176, 828, 265, 65, 326, 359, 919, 514, 868]
[65, 176, 265, 326, 359, 514, 613, 828, 868, 919]
4b) Write a program to convert Roman numbers into integer values using
dictionaries.
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:
Enter a Roman Number: XVII
17
PROGRAM -5
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:
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
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:
+918151894220
+829392938876
+918768456234
prakash81.82@gmail.in
PROGRAM -6
6a) Write a python program to accept a file name from the user and perform
the following operations.
2. Find the frequency of occurrence of the word accepted by the user in the
file
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:
6b) Write a Python program to create a ZIP file of a particular folder that
contains several files inside it.
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)
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
OUTPUT:
Enter Directory name that you want to backup : zipDemo
Archive myZip.zip created successfully.
PROGRAM -7
7a) By using the concept of inheritance write a python program to find the
area of a 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):
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:
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 the 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)
def updtSalary(self):
self.salary = int(input("Enter new Salary : "))
print("Updated Salary", self.salary)
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
OUTPUT:
Enter Employee name: Sameer
Employee Details
Name: Sameer
ID: A123
Dept: CSE
Salary: 85750
PROGRAM -8
8a) Write a Python program to find 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
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:
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
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...
9b) Demonstrate a python program to read the data from the spreadsheet and
write the data into the spreadsheet.
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"]
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)
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:
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
10a) Write a Python program to combine select pages from many PDFs.
num = int(input("Enter page number you want combine from multiple documents
"))
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)
OUTPUT:
Initially take any two pdf files and chose first three pages to combine and give the
result in an output file.
10b) Write a Python program to fetch current weather data from the JSON
file.
import json
with open('weather_data.json') as f:
data = json.load(f)
current_temp = data['main']['temp']
humidity = data['main']['humidity']
weather_desc = data['weather'][0]['description']
print(f"Humidity: {humidity}%")
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
VIVA QUESTIONS:
What is Python?
1. Python is one of the most widely-used and popular programming languages, was developed by Guido van
Rossum and released first on February 20, 1991.
2. Python is a free and open-source language with a very simple and clean syntax which makes it easy for
developers to learn Python.
3. It supports object-oriented programming and is most commonly used to perform general-purpose
programming.
4. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial
Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development, Web
Scraping, and various other domains, System Scripting, Software Development, Complex Mathematics.
What are the benefits of using Python language as a tool in the present scenario?
The following are the benefits of using Python language:
Object-Oriented Language, High-Level Language, Dynamically Typed language, Extensive support Libraries,
Presence of third-party modules, Open source and community development, Portable and Interactive, Portable
across Operating systems.
Is Python a compiled language or an interpreted language?
Python is a partially compiled language and partially interpreted language. ‘#’ is used to comment on
everything that comes after on the line.
Difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
What is a lambda function?
A lambda function is an anonymous function. This function can have any number of parameters but, can have
just one statement.
Pass means performing no operation or in other words, it is a placeholder in the compound statement, where
there should be a blank left and nothing has to be written there.
Python documentation strings (or docstrings) provide a convenient way of associating documentation with
Python modules, functions, classes, and methods.
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes”””
just below the class, method, or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the
help function.
PIP is an acronym for Python Installer Package which provides a seamless interface to install various
Python modules. It is a command-line tool that can search for packages over the internet and install them
without any user interaction.