0% found this document useful (0 votes)
3 views

lab manual python

The document outlines multiple Python programs covering various functionalities, including reading files, counting word frequency, zipping folders, calculating areas of shapes using inheritance, managing employee details, checking for palindromes, downloading comics, and reading/writing spreadsheets. Each program is explained with code snippets and descriptions of their operations. The document serves as a comprehensive guide for implementing these functionalities in Python.

Uploaded by

Nidhi Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lab manual python

The document outlines multiple Python programs covering various functionalities, including reading files, counting word frequency, zipping folders, calculating areas of shapes using inheritance, managing employee details, checking for palindromes, downloading comics, and reading/writing spreadsheets. Each program is explained with code snippets and descriptions of their operations. The document serves as a comprehensive guide for implementing these functionalities in Python.

Uploaded by

Nidhi Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

6a.

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
In summary, the display_first_N_lines function takes a file name and a
number N as inputs, opens the file, reads and displays the first N lines
from the file (stripping any leading or trailing whitespace), and handles
the case where the file is not found by printing an error message. The use
of the with statement ensures that the file is properly managed and
closed after reading the lines.
def display_first_N_lines(file_name, N):
try:
with open(file_name, 'r') as file:
for i in range(N):
line = file.readline().strip()
if not line:
break
print(line)
except FileNotFoundError:
print("File not found!")
In summary, the find_word_frequency function takes a file name and a
word as inputs, opens the file, reads its content, counts the occurrences of
the given word, and returns either the frequency of the word or an error
message if the file is not found. The use of the with statement ensures
that the file is properly managed and closed after reading its con
def find_word_frequency(file_name, word):
try:
with open(file_name, 'r') as file:
content = file.read()
frequency = content.count(word)
return frequency
except FileNotFoundError:
return "File not found!"
In summary, the code within the if __name__ == "__main__": block is
responsible for taking user inputs: the file name and the number of lines
to display. The input() function is used to capture user inputs, and the
entered values are stored in the variables file_name and N respectively.
This input collection allows the program to interact with the user and
gather the necessary information before proceeding with further
operations.
if __name__ == "__main__": This conditional statement checks
whether the current script is being run directly as the main program or if it
is being imported as a module into another script. The code within this
block will only run if the script is being executed directly.
is a common construct used in Python to check whether the script is being
run as the main program or if it is being imported as a module into
another script.
In Python, the double underscore ( __) has special significance and is used
for various purposes, often referred to as "magic" or "dunder" methods
(short for "double underscore methods")
Certain variables, like __name__ and __file__, are built-in and automatically
set by Python. They provide information about the current module or
script being executed
file_name = input("Enter the file name: ")
N = int(input("Enter the number of lines to
display: "))

display_first_N_lines(file_name, N) This line calls the


display_first_N_lines function that you defined earlier. It passes the values
of file_name and N as arguments to the function. This will display the first
N lines from the specified file.

word_to_find = input("Enter the word to find


frequency: ") This line prompts the user to enter a word for which
they want to find the frequency in the file. The entered text is stored in
the variable word_to_find.
frequency = find_word_frequency(file_name,
word_to_find) This line calls the find_word_frequency function, passing
the file_name and word_to_find as arguments. The function will calculate
the frequency of the entered word in the specified file and return the
result, which is then stored in the variable frequency.
print(f"Frequency of '{word_to_find}' in the file:
{frequency}") This line prints the frequency of the entered word in
the file. The f before the string indicates a formatted string, allowing you
to embed variables (like word_to_find and frequency) within the string
using curly braces {}. The values of these variables will be inserted into
the string when it's printed.
to check output
create a text file named "example.txt" with the following content:
This is an example file.
It contains some lines of text
for demonstrating the Python program.
Let's see how it works!

6b. Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
import os
import zipfile
 import os: This module provides a way to use operating system-
dependent functionality.
 import zipfile: This module provides tools for creating, reading, and
extracting ZIP archives.

def zip_folder(folder_path, output_zip_filename):


his function takes two arguments: folder_path (the path of the folder to be
zipped) and output_zip_filename (the name of the output ZIP file).
with zipfile.ZipFile(output_zip_filename, 'w',
zipfile.ZIP_DEFLATED) as zipf:
he 'w' mode stands for "write," indicating that you want to create a new
ZIP archive or overwrite an existing one. If the file doesn't exist, it will be
created. If it already exists, its contents will be replaced.
This specifies the compression method to use for the archive. In this case,
zipfile.ZIP_DEFLATED indicates that the contents of the ZIP archive should
be compressed using the DEFLATE compression algorithm. This helps
reduce the size of the resulting ZIP file by compressing the individual files
within the archive.
for root, _, files in os.walk(folder_path):
root: This variable represents the current directory being visited during
the traversal. It starts from the specified folder_path and progresses
through all subdirectories.
_: This is a placeholder variable used to represent the subdirectories
within the current directory

os.walk() function generates a sequence of tuples as it traverses through


the directory structure. Each tuple contains three elements: the root
directory, a list of subdirectories (which we're ignoring using _), and a list
of filenames (which we're capturing using files).
for file in files:
file_path = os.path.join(root, file)
This line creates the full path to the current file by joining the root
directory (root) and the file name ( file) using os.path.join.
arcname = os.path.relpath(file_path,
folder_path)
This line computes the relative path of the current file with respect to the
folder_path. The os.path.relpath function is used to determine the relative
path.
zipf.write(file_path, arcname)
line writes the current file ( file_path) to the ZIP archive with the specified
relative path ( arcname). This effectively adds the file to the ZIP archive.

if __name__ == "__main__":
is a common construct used in Python to check whether the script is being
run as the main program or if it is being imported as a module into
another script.
In Python, the double underscore ( __) has special significance and is used
for various purposes, often referred to as "magic" or "dunder" methods
(short for "double underscore methods")
Certain variables, like __name__ and __file__, are built-in and automatically
set by Python. They provide information about the current module or
script being executed.
# Replace this with the path of the folder you want
to zip
folder_to_zip = "C:\Users\DELL\Documents\dummy"
# Replace this with the desired name of the output
ZIP file
output_zip_file = "dummy.zip"

zip_folder(folder_to_zip, output_zip_file)
print(f"Folder '{folder_to_zip}' has been zipped to
'{output_zip_file}'

This calls the zip_folder function with the provided folder path and output
ZIP file name. After zipping is complete, it prints a message indicating the
success of the operation.
7. a By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle.
this code demonstrates the concept of inheritance and polymorphism in
object-oriented programming. It defines a base class Shape with
subclasses Triangle, Circle, and Rectangle, each implementing its own
area() method to calculate the area of the respective shape.
import math
mports the math module, which provides mathematical functions and
constants, including pi.

class Shape:
def area(self):
pass
defines a base class Shape with a method area() that is left undefined
(using the pass statement). This method is intended to be overridden by
subclasses to calculate the area of specific shapes.

class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height

def area(self):
return 0.5 * self.base * self.height
This defines a subclass Triangle that inherits from the Shape class. It has
an __init__ method to initialize the base and height attributes. The area()
method is overridden to calculate the area of a triangle using the formula
0.5 * base * height .

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2
This defines another subclass Circle that also inherits from Shape. It has
an __init__ method to initialize the radius attribute. The area() method
calculates the area of a circle using the formula π * radius^2.
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width
This defines a third subclass Rectangle that inherits from Shape. It
initializes the length and width attributes using an __init__ method. The
area() method calculates the area of a rectangle using the formula length
* width.

if __name__ == "__main__":
This line checks if the script is being run as the main program.
triangle = Triangle(6, 4)
print("Area of Triangle:", triangle.area())
These lines create an instance of the Triangle class with a base of 6 and a
height of 4. It then calls the area() method on the triangle object to
calculate and print the area of the triangle.
circle = Circle(5)
print("Area of Circle:", circle.area())
These lines create an instance of the Circle class with a radius of 5. It then
calls the area() method on the circle object to calculate and print the area
of the circle.
rectangle = Rectangle(7, 3)
print("Area of Rectangle:", rectangle.area())
These lines create an instance of the Rectangle class with a length of 7
and a width of 3. It then calls the area() method on the rectangle object to
calculate and print the area of the rectangle.

7. 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.
class Employee:
def __init__(self, name, employee_id, department,
salary):
self.name = name
self.employee_id = employee_id
self.department = department
self.salary = salary

def update_salary_by_department(self, department,


new_salary):
if self.department == department:
self.salary = new_salary

def __str__(self):
return f"Name: {self.name}, Employee ID:
{self.employee_id}, Department: {self.department},
Salary: {self.salary}"

if __name__ == "__main__":
employees = [
Employee("A", 1001, "HR", 50000),
Employee("B", 1002, "IT", 60000),
Employee("C", 1003, "HR", 55000),
Employee("D", 1004, "Finance", 70000),
]

for emp in employees:


print(emp)

department_to_update = "HR"
new_salary_for_department = 58000

for emp in employees:

emp.update_salary_by_department(department_to_update,
new_salary_for_department)

print("\nAfter updating salaries:")


for emp in employees:
print(emp)

8 a 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.
Method overriding is a fundamental concept in polymorphism, which
allows objects of different classes to be treated as objects of a common
superclass. It promotes code reusability and helps maintain a clear and
modular code structure.
Polymorphism is a key concept in object-oriented programming that
allows objects of different classes to be treated as objects of a common
superclass.

class PalindromeChecker:
def is_palindrome(self, input_value):
raise NotImplementedError("Subclasses must
implement this method")

class StringPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
input_value = input_value.lower().replace(" ",
"") # Ignore case and spaces
return input_value == input_value[::-1]

class IntegerPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
return str(input_value) == str(input_value)[::-
1]

def check_palindrome(palindrome_checker, input_value):


if palindrome_checker.is_palindrome(input_value):
return f"'{input_value}' is a palindrome."
else:
return f"'{input_value}' is not a palindrome."

if __name__ == "__main__":
input_value = input("Enter a string or an integer:
")

if input_value.isdigit():
checker = IntegerPalindrome()
else:
checker = StringPalindrome()

result = check_palindrome(checker, input_value)


print(result)

9a) Write a python program to download the all XKCD comics


import os
import requests
from IPython.display import Image, display

def download_xkcd_comics(output_folder):
os.makedirs(output_folder, exist_ok=True)

url = 'https://xkcd.com/{}/info.0.json'
comic_number = 1
while True:
response =
requests.get(url.format(comic_number))
if response.status_code == 200:
comic_data = response.json()
image_url = comic_data['img']
image_response = requests.get(image_url)

if image_response.status_code == 200:
The condition if response.status_code == 200: is used to check if the HTTP
request was successful. If the status code returned by the server is 200, it
indicates that the requested resource (in this case, the comic data or
image) is available and can be processed further.
For other status codes, such as "404 Not Found" (resource not found) or
"500 Internal Server Error" (server error),
image_name =
os.path.basename(image_url)
image_path =
os.path.join(output_folder, image_name)

with open(image_path, 'wb') as


image_file:

image_file.write(image_response.content)

display(Image(filename=image_path))
else:
print(f"Failed to download image for
comic {comic_number}")
else:
break

comic_number += 1

if __name__ == "__main__":
output_folder = 'xkcd_comics'
download_xkcd_comics(output_folder)

9 b) Demonstrate python program to read the data from the spreadsheet and write the data in to the
spreadsheet
1. Open a Jupyter Notebook or JupyterLab session.
2. In a code cell, use the following command to install openpyxl:
pythonCopy code
!pip install openpyxl

3. Run the code cell by clicking the "Run" button or by pressing Shift +
Enter.

import openpyxl

def read_spreadsheet(file_path):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active

for row in sheet.iter_rows(min_row=2,


values_only=True):
name, age, city = row
print(f"Name: {name}, Age: {age}, City:
{city}")

workbook.close()

def write_spreadsheet(file_path):
workbook = openpyxl.Workbook()
sheet = workbook.active

sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet["C1"] = "City"

data = [
("Alice", 28, "New York"),
("Bob", 32, "San Francisco"),
("Charlie", 24, "Los Angeles")
]

for row in data:


sheet.append(row)

workbook.save(file_path)
workbook.close()
if __name__ == "__main__":
read_file_path = "C:\\Users\\DELL\\data.xlsx"
write_file_path = "C:\\Users\\DELL\\output.xlsx"

# Write data to a spreadsheet


write_spreadsheet(write_file_path)
print("Data written to spreadsheet.")

# Read data from a spreadsheet


10
a) Write a python program to combine select pages from many PDFs

pip install PyPDF2

PROGRAM
import PyPDF2

def combine_selected_pages(input_pdfs, output_pdf,


selected_pages):
pdf_writer = PyPDF2.PdfWriter()

for pdf_file, page_numbers in zip(input_pdfs,


selected_pages):
pdf_reader = PyPDF2.PdfReader(pdf_file)

for page_number in page_numbers:


if 1 <= page_number <=
len(pdf_reader.pages):
page = pdf_reader.pages[page_number -
1]
pdf_writer.add_page(page)

with open(output_pdf, 'wb') as output_file:


pdf_writer.write(output_file)

# List of input PDFs, corresponding page numbers to


select
input_pdfs = ['new.pdf', 'new1.pdf']
selected_pages = [[1, 3], [2]]

output_pdf = 'combined_pages.pdf'

combine_selected_pages(input_pdfs, output_pdf,
selected_pages)
print(f'Selected pages from input PDFs combined and
saved as {output_pdf}')

10 b) Write a python program to fetch current weather data from the JSON file

A JSON (JavaScript Object Notation) file


1.Open a text editor that supports text editing.
2.Write the JSON data into the text editor. Ensure that the syntax adheres to the JSON
format rules.

3.JSON DATA TO BE SAVED


{
"city": "City Name",
"temperature": 70,
"conditions": "Sunny"
}
4.Save the file with a .json file extension. Choose an appropriate name for your JSON file.
For example, you can save it as data.json.
5. save the file in the same directory as your Python script
PROGRAM
import json

def fetch_weather_data(file_name):
try:
with open(file_name, 'r') as json_file:
weather_data = json.load(json_file)
return weather_data
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
return None
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in
'{file_name}'.")
return None

def display_weather_data(weather_data):
if weather_data is not None:
print("Weather Information:")
print(f"City: {weather_data['city']}")
print(f"Temperature:
{weather_data['temperature']}°F")
print(f"Conditions:
{weather_data['conditions']}")

# Fetch weather data from JSON file


file_name = 'data.json'
weather_data = fetch_weather_data(file_name)

# Display weather data


display_weather_data(weather_data)

You might also like