lab manual python
lab manual python
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: "))
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.
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 __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),
]
department_to_update = "HR"
new_salary_for_department = 58000
emp.update_salary_by_department(department_to_update,
new_salary_for_department)
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]
if __name__ == "__main__":
input_value = input("Enter a string or an integer:
")
if input_value.isdigit():
checker = IntegerPalindrome()
else:
checker = StringPalindrome()
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)
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
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")
]
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"
PROGRAM
import PyPDF2
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
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']}")