Program 6(A) –
import os.path
import sys
fname = input("Enter the filename : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
lineList = infile.readlines()
for i in range(5): //Change this range as per the number of lines you are giving
in text file.
print(i+1, ":", lineList[i])
word = input("Enter a word : ")
cnt = 0
for line in lineList:
cnt += line.count(word)
print("The word", word, "appears", cnt, "times in the file")
Output –
Enter the filename: /Users/anjanisharan/Desktop/Hello.txt
1 : Hello,
2 : Test File, Counting number of lines
3 : Hello,
4 : Hi,
5 : Bye.
Enter a word: Hello
The word Hello appears 2 times in the file
Program 6(B) –
import os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup : ")
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Output –
Enter Directory name that you want to backup :
D:\RNSIT\2.Even_Semester\4sem_PythonProgramming\LabPrograms
Archive myZip.zip created successfully
Program 7(A) –
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:
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
Program 7(B) –
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 : Ganapathi
Enter Employee ID : 1234
Enter Employee Dept : AI&ML
Enter Employee Salary : 100000
Employee Details
Name : Ganesh
ID : 1234
Dept : AI&ML
Salary : 100000
Enter new Salary : 150000
Updated Salary 150000
Program 8(A) – //Program 8 only has one part.
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 : 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(A) –
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/radians_are_cursed.png...
Downloading https://imgs.xkcd.com/comics/presents_for_biologists.png...
Program 9(B) –
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")
lang = ["Kannada", "Telugu", "Tamil"]
state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Language"
sheet.cell(row = 1, column = 3).value = "Code"
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = lang[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("demo.xlsx")
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(A) –
from PyPDF2 import PdfWriter, PdfReader
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)
print(“PDF merged successfully”)
OUTPUT:
Enter page number you want combine from multiple documents 3
PDF merged successfully.
Program 10(B) –
import json
# Load the JSON data from file
with open('weather_data.json') as f:
data = json.load(f)
# Extract the required weather data
current_temp = data['main']['temp']
humidity = data['main']['humidity']
weather_desc = data['weather'][0]['description']
# Display the weather data
print(f"Current temperature: {current_temp}°C")
print(f"Humidity: {humidity}%")
print(f"Weather description: {weather_desc}")
OUTPUT:
Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky
Part B Programs
1. Linear Search
list=[]
n=int(input("Enter number of elements:"))
print("Enter the list elements") #Press enter after every single input
for i in range(0,n):
ele=int(input())
list.append(ele)
key = int(input("Enter the element to search for: "))
index_found = -1
for i in range(len(list)):
if list[i] == key:
index_found = i
break
if index_found != -1:
print(f"Element {key} found at index {index_found}")
else:
print(f"Element {key} not found in the list")
Output –
Enter number of elements:5
Enter the list elements
1
2
3
4
5
Enter the element to search for: 5
Element 5 found at index 4
2. Binary Search
list = []
n = int(input("Enter number of elements:"))
print("Enter the list elements")
for i in range(0, n):
ele = int(input())
list.append(ele)
key = int(input("Enter the value to search:"))
low = 0
high = len(list) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if list[mid] == key:
result = mid
break
elif list[mid] < key:
low = mid + 1
else:
high = mid - 1
if result != -1:
print(f"Element {key} found at index {result}")
else:
print(f"Element {key} not found in the list")
Output –
Enter number of elements:5
Enter the list elements
5
6
7
8
9
Enter the value to search:9
Element 9 found at index 4
3. Fibonacci Sequence
n = int(input("Enter the number of Fibonacci terms to generate: "))
a, b = 0, 1
if n < 2:
print("Please enter a number greater than or equal to 2.")
else:
print(a, b, end=" ")
for _ in range(2, n):
next_term = a + b
print(next_term, end=" ")
a, b = b, next_term
print()
Output –
Enter the number of Fibonacci terms to generate: 5
01123
4. List creation and five list operation
my_list=[]
n=int(input("Enter number of elements:"))
print("Enter the list elements")
for i in range(0,n):
ele=int(input())
my_list.append(ele)
print("Original List:", my_list)
my_list.append(6)
print("After Append:", my_list)
my_list.insert(2, 10)
print("After Insert:", my_list)
my_list.remove(3)
print("After Remove:", my_list)
my_list[0] = 0
print("After Modify:", my_list)
subset = my_list[2:5]
print("Subset of List:", subset)
Output –
Enter number of elements:5
Enter the list elements
1
2
3
4
5
Original List: [1, 2, 3, 4, 5]
After Append: [1, 2, 3, 4, 5, 6]
After Insert: [1, 2, 10, 3, 4, 5, 6]
After Remove: [1, 2, 10, 4, 5, 6]
After Modify: [0, 2, 10, 4, 5, 6]
Subset of List: [10, 4, 5]
5. Dictionary creation and five dictionary operation
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print("Original Dictionary:", my_dict)
name = my_dict['name']
print("Name:", name)
my_dict['age'] = 31
print("Modified Dictionary:", my_dict)
my_dict['gender'] = 'Female'
print("After Adding:", my_dict)
if 'city' in my_dict:
del my_dict['city']
print("After Removing:", my_dict)
if 'age' in my_dict:
print("Age exists in the dictionary")
else:
print("Age does not exist in the dictionary")
Output –
Original Dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Name: Alice
Modified Dictionary: {'name': 'Alice', 'age': 31, 'city': 'New York'}
After Adding: {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender': 'Female'}
After Removing: {'name': 'Alice', 'age': 31, 'gender': 'Female'}
Age exists in the dictionary