Program 6(A) –
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(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 += [Link](word)
print("The word", word, "appears", cnt, "times in the file")
Output –
Enter the filename: /Users/anjanisharan/Desktop/[Link]
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 [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 :
D:\RNSIT\2.Even_Semester\4sem_PythonProgramming\LabPrograms
Archive [Link] created successfully
Program 7(A) –
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
Program 7(B) –
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 : 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):
[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(A) –
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]
Program 9(B) –
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(A) –
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)
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 = [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}")
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())
[Link](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())
[Link](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