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

Python Q22-29 print (2)

The document contains a series of Python programming exercises covering file operations, class definitions, date calculations, and inheritance. It includes code examples for creating and manipulating text and binary files, defining classes with methods, and demonstrating the use of inheritance and the super() function. Each exercise is followed by code snippets and expected outputs.

Uploaded by

mishraashok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Q22-29 print (2)

The document contains a series of Python programming exercises covering file operations, class definitions, date calculations, and inheritance. It includes code examples for creating and manipulating text and binary files, defining classes with methods, and demonstrating the use of inheritance and the super() function. Each exercise is followed by code snippets and expected outputs.

Uploaded by

mishraashok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Programming MCA-166P 35113704424

Q22. Create a text file and Perform the following operations on the file
a) Open the file and Read the contents from the file.
b) Check if the file exists or not
c) Write the content and display
d) Append the content to the existing file and display it
e) Remove the file

Code:

import os
filename = "example.txt"

# a)
try:
with open(filename, "r") as file:
print("File Contents:\n", file.read())
except FileNotFoundError:
print("File does not exist.")

# b)
if os.path.exists(filename):
print(f"{filename} exists.")
else:
print(f"{filename} does not exist.")

# c)
with open(filename, "w") as file:
file.write("This is a test file created by Pranjal.\n")
print("Content written to file.")

# d)
with open(filename, "a") as file:
file.write("Appending more content to the file.\n")
print("Content appended.")

# e)
os.remove(filename)
print(f"{filename} has been deleted.")

Output:

Page 29
Python Programming MCA-166P 35113704424

Q23.Write a program to copy the contents of one file into a new file.
i. The operations should be performed only if the file exists and user permits to
overwrite the content of the destination file.
ii. Delete the source file once the contents are copied to destination file

Code:

# copy_file.py
import os
import shutil

source_file = "source.txt"
destination_file = "destination.txt"

with open(source_file, "w") as file:


file.write("This is the source file content.")

if os.path.exists(source_file):
choice = input(f"{destination_file} will be overwritten. Continue? (yes/no):
").strip().lower()
if choice == 'yes':
shutil.copy(source_file, destination_file)
print(f"Copied content from {source_file} to {destination_file}.")
os.remove(source_file)
print(f"{source_file} has been deleted.")
else:
print("Operation aborted.")
else:
print("Source file does not exist.")

Output:

Page 30
Python Programming MCA-166P 35113704424

Q24.Create a binary file with roll number, name and marks. Input a roll number and
perform the following operations:
• update the marks.
• Delete the record
• Display the record
• Append the record
• Search the record

Code:

import pickle
import os

filename = "students.dat"

def append_record():
with open(filename, "ab") as file:
record = {'roll_no': 101, 'name': 'Pranjal', 'marks': 90}
pickle.dump(record, file)
print("Record appended.")

def display_records():
try:
with open(filename, "rb") as file:
while True:
try:
record = pickle.load(file)
print(record)
except EOFError:
break
except FileNotFoundError:
print("File not found.")

append_record()
display_records()

Output:

Page 31
Python Programming MCA-166P 35113704424

Q25.Write a Python program that defines a class Rectangle with:


i) A constructor (__init__) that takes length and width as parameters.
ii) A method area() that calculates and returns the area of the rectangle.
iii)A method perimeter() that calculates and returns the perimeter of the rectangle.
iv)A static method is_square(length, width) that returns True if the given dimensions
form a square, otherwise False.
v) Create an instance of Rectangle with length = 5 and width = 10, and print the area
and perimeter.
vi) use the static method to check if it's a square.

Code:

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def perimeter(self):
return 2 * (self.length + self.width)

@staticmethod
def is_square(length, width):
return length == width

rect = Rectangle(5, 10)


print("Area:", rect.area())
print("Perimeter:", rect.perimeter())
print("Is Square:", Rectangle.is_square(5, 10))

Output:

Page 32
Python Programming MCA-166P 35113704424

Q26.You are building a scheduling system and need to calculate future and past dates.
Write a Python program that:
1. Gets the current date and time using datetime.now().
2. Calculates and prints the date 7 days from now.
3. Calculates and prints the date 30 days ago.
4. Asks the user to enter a number of days and then calculates and prints the date that
many days from today.

Code:

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Date:", current_date)

future_date = current_date + timedelta(days=7)


print("Date 7 days from now:", future_date)

past_date = current_date - timedelta(days=30)


print("Date 30 days ago:", past_date)

days = int(input("Enter number of days: "))


custom_date = current_date + timedelta(days=days)
print(f"Date after {days} days:", custom_date)

Output:

Page 33
Python Programming MCA-166P 35113704424

Q27.Use timedelta from the datetime module to perform date calculations.


Write a Python program that demonstrates multiple inheritance, where:
• A Parent class Person has an attribute name and a method show_name().
• Another Parent class Job has an attribute designation and a method show_job().
• A Child class Employee inherits from both Person and Job and has an additional
attribute salary.
• Create an object of Employee and call all the methods.

Code:

class Person:
def __init__(self, name):
self.name = name

def show_name(self):
print("Name:", self.name)

class Job:
def __init__(self, designation):
self.designation = designation

def show_job(self):
print("Designation:", self.designation)

class Employee(Person, Job):


def __init__(self, name, designation, salary):
Person.__init__(self, name)
Job.__init__(self, designation)
self.salary = salary

def show_salary(self):
print("Salary:", self.salary)

emp = Employee("Pranjal", "Software Engineer", 75000)


emp.show_name()
emp.show_job()
emp.show_salary()

Output:

Page 34
Python Programming MCA-166P 35113704424

Q28. Write a Python program that demonstrates the use of super() by:
1. Creating a Parent class Vehicle with an __init__() method to initialize brand.
2. Creating a Child class Car that inherits from Vehicle and adds an attribute model.
3. Use super() in Car to call the parent class constructor inside its __init__() method.
4. Create an object of Car and print both brand and model.

Code:

class Vehicle:
def __init__(self, brand):
self.brand = brand

class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model

def show_details(self):
print("Brand:", self.brand)
print("Model:", self.model)

car = Car("Toyota", "Corolla")


car.show_details()

Output:

Page 35
Python Programming MCA-166P 35113704424

Q29. Write a Python program using inheritance, where:


i. Create a Parent class Employee with attributes name and salary.
ii. Define a method show_details() in Employee to display the employee’s name and
salary.
iii. Create a Child class Manager that inherits from Employee and has an additional
attribute department.
iv. Override the show_details() method in Manager to display all details, including
department.
v. Use super() in the Manager class to call the parent class constructor.
vi. Create an object of Manager and print the details.

Code:

class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary

def show_details(self):
print(f"Employee Name: {self.name}")
print(f"Salary: {self.salary}")

class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary)
self.department = department

def show_details(self):
super().show_details()
print(f"Department: {self.department}")

manager = Manager("Pranjal", 80000, "IT")

manager.show_details()

Output:

Page 36

You might also like