PROGRAM: 6
Aim: Demonstration of reading, writing and organizing files.
File Operations
6.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
inputFile = "textfile.txt"
N = int(input("Enter N value: "))
with open(inputFile, 'r') as filedata:
linesList= filedata.readlines()
print("The following are the first",N,"lines of a text file:")
for textline in (linesList[:N]):
print(textline, end ='')
filedata.close()
word=input("Enter word to be searched:")
k=0
with open(inputFile, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print(f"Occurrences of the word {word} is:" , k )
OUTPUT:
Enter N value: 3
The following are the first 3 lines of a text file:
Welcome To Python Programming
Studying in computer science branch at JIT
Import the regex module with import re.
Enter word to be searched: JIT
Occurrences of the word JIT is: 1
Zip File Creation
6.b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
import os
from zipfile import ZipFile
# Create object of ZipFile
with ZipFile('E:/Zipped file.zip', 'w') as zip_object:
# Traverse all files in directory
for folder_name, sub_folders, file_names in os.walk('E:/python files'):
for filename in file_names:
# Create filepath of files in directory
file_path = os.path.join(folder_name, filename)
# Add files to zip file
zip_object.write(file_path, os.path.basename(file_path))
if os.path.exists('E:/Zipped file.zip'):
print("ZIP file created")
else:
print("ZIP file not created")
OUTPUT:
PROGRAM 7
Aim: Demonstration of the concepts of classes, methods, objects and inheritance
Inheritance
7a. By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle.
class Shape:
def area(self):
pass
class Triangle(Shape):
def __init__ (self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__ (self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
b=int(input("Enter the value of base"))
h=int(input("Enter the value of height"))
triangle = Triangle(b,h)
print("Area of the Triangle:", triangle.area())
r=int(input("Enter the value of radius"))
circle = Circle(r)
print ("Area of the Circle:", circle.area())
l=int(input("Enter the value of Length"))
w=int(input("Enter the value of width"))
rectangle = Rectangle(l, w)
print ("Area of the Rectangle:", rectangle.area())
OUTPUT:
Enter the value of base5
Enter the value of height6
Area of the Triangle: 15.0
Enter the value of radius5
Area of the Circle: 78.5
Enter the value of Length6
Enter the value of width7
Area of the Rectangle: 42
Employee Details
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 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 updateSalary(self):
self.salary = int(input("Enter new Salary : "))
print("Updated Salary", self.salary)
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updateSalary()
OUTPUT:
Enter Employee name : RAM
Enter Employee ID : 1607
Enter Employee Dept : CSE
Enter Employee Salary : 45000
Employee Details
Name : RAM
ID : 1607
Dept : CSE
Salary : 45000
Enter new Salary : 50000
Updated Salary 50000
Program 8
Aim: Demonstration of classes and methods with polymorphism and overriding
polymorphism and overriding
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.
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:
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")
else:
print("Given integer is not a Palindrome")
OUTPUT:
Enter a string : amma
Given string is a Palindrome
Enter a integer : 1221
Given integer is a Palindrome
Enter a string : qwer
Given string is not a Palindrome
Enter a integer : 1234
Given integer is not 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
b) Demonstrate python program to read the data from the spreadsheet
and write the data in to the spreadsheet
Download The All Xkcd Comics
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')
# 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.')
OUTPUT:
Downloading https://imgs.xkcd.com/comics/barrel_cropped_(1).jpg...
Downloading https://imgs.xkcd.com/comics/types_of_solar_eclipse.png...
Downloading https://imgs.xkcd.com/comics/car_wash.png...
Downloading https://imgs.xkcd.com/comics/perseids_pronunciation.png...
Downloading https://imgs.xkcd.com/comics/what_to_do.png...
Downloading https://imgs.xkcd.com/comics/solar_panel_placement.png...
Spread Sheet Operations
b)Demonstrate python program to read the data from the spreadsheet and
write the data in to the spreadsheet
from openpyxl import Workbook
from openpyxl.styles import Font
import pandas as pd
wb = Workbook()
sheet = wb.active
sheet.title = "studentdata"
Name = ["RAM", "JANU", "ARYA"]
College = ["JIT", "RNSIT", "SJBIT"]
Marks = ["89", "95", "98"]
sheet.cell(row = 1, column = 1).value = "Name"
sheet.cell(row = 1, column = 2).value = "College"
sheet.cell(row = 1, column = 3).value = "Marks"
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 = Name[i-2]
sheet.cell(row = i, column = 2).value = College[i-2]
sheet.cell(row = i, column = 3).value = Marks[i-2]
wb.save("9bprogram.xlsx")
# read by default 1st sheet of an excel file
data = pd.read_excel('9bprogram.xlsx')
print(data)
OUTPUT:
runfile('C:/Users/ddhin/exaample.txt/9b.py', wdir='C:/Users/ddhin/exaample.txt')
Name College Marks
0 RAM JIT 89
1 JANU RNSIT 95
2 ARYA SJBIT 98
PROGRAM: 10
Aim: Demonstration of working with PDF, word and JSON files
a)Write a python program to combine select pages from many PDFs
Merge selected pages from Multiple PDFs to a new PDF
from PyPDF2 import PdfWriter, PdfReader
num = int(input("Enter page number you want combine from multiple documents "))
pdf1 = open('CG9.pdf', 'rb')
pdf2 = open('CG12.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:
runfile('C:/Users/ddhin/exaample.txt/10A.py', wdir='C:/Users/ddhin/exaample.txt')
Enter page number you want combine from multiple documents3
Fetch Weather Data From JSON
b)Write a python program to fetch current weather data from the JSON file
import json
# Load the JSON data from file
with open('weather_data.json') as f:
data = json.load(f)
# Extract the required weather data
curr_temp = data['main']['temp']
humidity = data['main']['humidity']
weather_desc = data['weather'][0]['description']
# Display the weather data
print(f"Current temperature: {curr_temp}°C")
print(f"Humidity: {humidity}%")
print(f"Weather description: {weather_desc}")
OUTPUT:
Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky
Program 1
Aim: Introduce the Python fundamentals, data types, operators, flow control
and exception handling in Python
Calculation of Test Average
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.
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 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
Program 1(b)
Palindrome Check & Digit Occurrence Count
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.
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
Enter a value : 12321
Palindrome
1 appears 2 times
2 appears 2 times
3 appears 1 times
Program 2
Aim: Demonstrating creation of functions, passing parameters and return values
Fibonacci Sequence
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.
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
Note: Method 2
def fibonacci(n):
# first two terms
a, b = 0, 1
count = 0
# check if the number of terms is valid
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(a)
else:
print("Fibonacci sequence:")
while count < n:
print(a)
c=a+b
# update values of a and b
a=b
b=c
count += 1
# take input from the user
n = int(input("Enter the number of terms: "))
fibonacci(n)
Program2(b)
Binary to Decimal & Octal to Hexadecimal Conversion
Develop a python program to convert binary to decimal, octal to
hexadecimal using functions.
def binaryToDecimal(binary):
decimal, i ,= 0, 0
while(binary!= 0):
dec = binary % 10
decimal = decimal+ dec * pow(2, i)
binary = binary//10
i += 1
print(decimal)
binaryToDecimal(0b0011)
def octTOHex(n):
print("octal= ",n)
decnum=int(n,8)
hexadecimal=hex(decnum).replace("0x","")
print("equivalent hexadecimalvalue =",hexadecimal)
octTOHex('5123')
Output:
3
octal= 5123
equivalent hexadecimalvalue = a53
NOTE:METHOD2 Octal To Hexadecimal
octl_num = int(input("Enter some random number = "))
k=0
Hexa_deciml = ['0']*50
deciml_num = 0
tempry = 0
print( "The Hexadecimal value of the given octal number {", octl_num, "} is: ")
while octl_num != 0:
a = (octl_num % 10)
b = pow(8, tempry)*a
deciml_num = deciml_num+b
tempry += 1
octl_num = octl_num // 10
while deciml_num != 0:
remindr = deciml_num % 16
if remindr < 10:
chrvalue = chr(remindr+48)
Hexa_deciml[k] = chrvalue
k += 1
else: chrvalue = chr(remindr+55)
Hexa_deciml[k] = chrvalue
k += 1
deciml_num //= 16
for itr in range(k-1, -1, -1):
print(Hexa_deciml[itr], end='')
OUTPUT:
Enter some random number = 56
The Hexadecimal value of the given octal number { 56 } is:
2E
Program 3
Aim: Demonstration of manipulation of strings using string methods
Sentence Statistics
3(awrite a Python program that accepts a sentence and find the number of
words, digits, uppercase letters and lowercase letters.
s = input("Enter a sentence: ")
w, d, u, l = 0, 0, 0, 0
l_w = s.split()
w = len(l_w)
for c in s:
if c.isdigit():
d=d+1
elif c.isupper():
u=u+1
elif c.islower():
l=l+1
print ("No of Words: ", w)
print ("No of Digits: ", d)
print ("No of Uppercase letters: ", u)
print ("No of Lowercase letters: ", l)
Output:
Enter a sentence: weLCome To jit 2023
No of Words: 4
No of Digits: 4
No of Uppercase letters: 3
No of Lowercase letters: 9
Enter a sentence: Rama went to Devaraja market to pick 2 kgs of vegetable
No of Words: 11
No of Digits: 1
No of Uppercase letters: 2
No of Lowercase letters: 42
String Similarity
3(b)Write a Python program to find the string similarity between two given
strings.
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: 3B Method2
from difflib import SequenceMatcher
string1 = "Python Exercises"
string2 = "Python Exercise"
similarity = SequenceMatcher(None, string1, string2).ratio()
print("Original string:")
print(string1)
print(string2)
print("Similarity between two said strings:")
print(similarity)
OUTPUT:
Original string:
Python Exercises
Python Exercise
Similarity between two said strings:
0.967741935483871
Program 4
Aim: Discuss different collections like list, tuple and dictionary
Insertion Sort & Merge Sort on lists
4(a).Write a python program to implement insertion sort and merge sort
using lists.
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(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]
ROMAN TO INTEGERS
4b. Write a program to convert roman numbers in to integer
values using Dictionaries.
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 : MXCD
1390
Enter a Roman Number : VII
7
Program 5:
Aim: Demonstration of pattern recognition with and without using regular
expressions
Check Phone Number
5a. Write a function called isphonenumber() to recognize a pattern
415-555- 4242 without using regular expression and also write the code
to recognize thesame pattern using regular expression.
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
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 : 456-789-7896
Without using Regular Expression
Valid phone number
Using Regular Expression
Valid phone number
Enter a phone number : 456-8989-765
Without using Regular Expression
Invalid phone number
Using Regular Expression
Invalid phone number
Search PhoneNumbers &email
5.b Develop a python program that could search the text in a file for
phone numbers (+919900889977) and email addresses
(
[email protected])
with open('filename.txt', 'r') as file:
text = file.read()
import re
phone_numbers = re.findall(r'\+91\d{10}', text)
email_addresses = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-
z]{2,}\b', text)
print("Phone numbers found:", phone_numbers)
print("Email addresses found:", email_addresses)
OUTPUT:
[email protected]
+917348878215
+919812569090
+916567976156
+917543679809