0% found this document useful (0 votes)
5 views15 pages

67 Python 2

The document contains a series of Python programming assignments focused on object-oriented programming concepts. It includes the implementation of classes such as Book, Student, Surface_Area, Employee, and BankAccount, along with methods for various functionalities like calculating areas, managing employee details, and handling exceptions. Each assignment is accompanied by sample code and output demonstrating the expected results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views15 pages

67 Python 2

The document contains a series of Python programming assignments focused on object-oriented programming concepts. It includes the implementation of classes such as Book, Student, Surface_Area, Employee, and BankAccount, along with methods for various functionalities like calculating areas, managing employee details, and handling exceptions. Each assignment is accompanied by sample code and output demonstrating the expected results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name : Krish Chauhan

Roll No : 67

Course : 5 Years Integrated [Link].(Cs) Sem - IV

Subject : Programming in Python - Practical


------------------------------------------------------------------------
Assignment - 2
------------------------------------------------------------------------

------------------------------------------------------------------------------------------
----

Question 1 : Define a Book class with attributes like title, author, and
no_of_pages (all strings). Implement constructor(s) to initialize these
attributes when creating a new Book object. Add a method called
describe_book() that prints a summary of the book's information.

------------------------------------------------------------------------------------------
----

class Book:

title = author = no_of_pages = " "

def __init__(self, title, author, no_of_pages):

[Link] = title

[Link] = author

self.no_of_pages = no_of_pages

def describe_book(self):

print(f"Title: {[Link]}")

print(f"Author: {[Link]}")
print(f"Number of Pages: {self.no_of_pages}")

book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", "180")

book2 = Book("To Kill a Mockingbird", "Harper Lee", "281")

book3 = Book("The Guide", "R.K. Narayan", "220")

book4 = Book("Train to Pakistan", "Khushwant Singh", "250")

book5 = Book("Midnight's Children", "Salman Rushdie", "536")

print("Book 1 : ")

book1.describe_book()

print("--------------------------")

print("Book 2 : ")

book2.describe_book()

print("--------------------------")

print("Book 3 : ")

book3.describe_book()

print("--------------------------")

print("Book 4 : ")

book4.describe_book()

print("--------------------------")

print("Book 5 : ")

book5.describe_book()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------
Book 1 :
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Number of Pages: 180
--------------------------
Book 2 :
Title: To Kill a Mockingbird
Author: Harper Lee
Number of Pages: 281
--------------------------
Book 3 :
Title: The Guide
Author: R.K. Narayan
Number of Pages: 220
--------------------------
Book 4 :
Title: Train to Pakistan
Author: Khushwant Singh
Number of Pages: 250
--------------------------
Book 5 :
Title: Midnight's Children
Author: Salman Rushdie
Number of Pages: 536

----------------------------------------------------------------------------------------------

Question 2 : Define class student with attributes like First_name, Last_name,


Course, batch_year, result). Apply constructor (s) to initialize the attributes
while creating new student object. Here, batch_year must be a passing year and
the result must be PASS or FAIL. Add a method to calculate the total number
of FAIL students. (static method).
--------------------------------------------------------------------
class Student:
fail_count = 0
def __init__(self, first_name, last_name, course, batch_year, result):
self.first_name = first_name
self.last_name = last_name
[Link] = course
self.batch_year = batch_year
[Link] = result

if [Link] == 'FAIL':
Student.fail_count += 1
def get_fail_count():
return Student.fail_count

student1 = Student("Rahul", "Gupta", "Engineering", 2022, "PASS")


student2 = Student("Priya", "Patil", "Medicine", 2021, "FAIL")
student3 = Student("Arun", "Kumar", "Computer Science", 2022, "FAIL")
student4 = Student("Sneha", "Sharma", "Business", 2023, "FAIL")
student5 = Student("Neha", "Verma", "Law", 2021, "PASS")

fail_count = Student.get_fail_count()
print(f"Total number of FAIL students: {fail_count}")

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

Total number of FAIL students: 3


-------------------------------------------------------------------
Question 3 : Define class Surface_Area which includes three methods with the
name Calculate_area() (Function Overloading). Each method accepts
parameter(s) to calculate area of circle, rectangle and triangle. Display the
result from calling of respective Calculate_area() as per the user’s request.
Design the menu-driven program.
--------------------------------------------------------------------
import math

class Surface_Area:
def calculate_circle_area(self, radius):
return [Link] * radius ** 2

def calculate_rectangle_area(self, length, breadth):


return length * breadth

def calculate_triangle_area(self, base, height):


return 0.5 * base * height

# Menu-driven program
def main():
surface = Surface_Area()
choice = 0

while choice != 4:
print("\n1. Calculate area of Circle")
print("2. Calculate area of Rectangle")
print("3. Calculate area of Triangle")
print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
radius = float(input("Enter the radius of the circle: "))
area = surface.calculate_circle_area(radius)
print(f"Area of the circle: {area:.2f}")
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
area = surface.calculate_rectangle_area(length, breadth)
print(f"Area of the rectangle: {area:.2f}")
elif choice == 3:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = surface.calculate_triangle_area(base, height)
print(f"Area of the triangle: {area:.2f}")
elif choice == 4:
print("Exiting...")
else:
print("Invalid choice. Please enter a valid option.")

main()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

1. Calculate area of Circle


2. Calculate area of Rectangle
3. Calculate area of Triangle
4. Exit
Enter your choice: 1
Enter the radius of the circle: 2.5
Area of the circle: 19.63

1. Calculate area of Circle


2. Calculate area of Rectangle
3. Calculate area of Triangle
4. Exit
Enter your choice: 2
Enter the length of the rectangle: 10
Enter the breadth of the rectangle: 5
Area of the rectangle: 50.00

1. Calculate area of Circle


2. Calculate area of Rectangle
3. Calculate area of Triangle
4. Exit
Enter your choice: 3
Enter the base of the triangle: 12.5
Enter the height of the triangle: 5
Area of the triangle: 31.25
1. Calculate area of Circle
2. Calculate area of Rectangle
3. Calculate area of Triangle
4. Exit
Enter your choice: 4
Exiting…
--------------------------------------------------------------------
Question 4 : Write a python program to create employee class that has
employee details (id, name, salary) and design a function that reads the
employee id from the user and display employee details along with the Net
salary after adding DA(15%), MA(5%), HRA(20%) and deducting PA(12%) from
the basic salary.
--------------------------------------------------------------------
class Employee:
def __init__(self, emp_id, name, salary):
self.emp_id = emp_id
[Link] = name
[Link] = salary

def calculate_net_salary(self):
basic_salary = [Link]
da = 0.15 * basic_salary
ma = 0.05 * basic_salary
hra = 0.20 * basic_salary
pa = 0.12 * basic_salary
net_salary = basic_salary + da + ma + hra - pa
return net_salary

def main():
# Creating a list of Employee objects with Indian names
employees = [
Employee(101, "Ramesh Kumar", 50000),
Employee(102, "Suresh Singh", 60000),
Employee(103, "Anjali Gupta", 45000),
Employee(104, "Priya Patel", 55000),
Employee(105, "Rakesh Panjwani", 25300)
]

emp_id = int(input("Enter employee ID: "))

found = False

for emp in employees:


if emp.emp_id == emp_id:
found = True
net_salary = emp.calculate_net_salary()
print(f"Employee ID: {emp.emp_id}")
print(f"Name: {[Link]}")
print(f"Basic Salary: {[Link]}")
print(f"Net Salary: {net_salary:.2f}")
break

else :
print("Employee not found!")

main()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

Enter employee ID: 102


Employee ID: 102
Name: Suresh Singh
Basic Salary: 60000
Net Salary: 76800.00
--------------------------------------------------------------------
Question 5 : Write a python program to overload the multiplication (*) operator
that can act on objects of NUM class having two members as no1 and no2.
--------------------------------------------------------------------
class NUM:
def __init__(self, no1, no2):
self.no1 = no1
self.no2 = no2

def __mul__(self, other):


result_no1 = self.no1 * other.no1
result_no2 = self.no2 * other.no2
return NUM(result_no1, result_no2)

def main():
num1 = NUM(3, 4)
num2 = NUM(2, 5)

result = num1 * num2

print(f"The result of multiplication is: ({result.no1}, {result.no2})")

main()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------
The result of multiplication is: (6, 20)
--------------------------------------------------------------------

Question 6 : Write a python program to create class time with


attributes hour and minutes. Add constructor(s) to initialize the
attributes. Overload ‘+’ operator to add two time (hh:mm) type objects to
show new added time.
--------------------------------------------------------------------
class Time:
def __init__(self, hour, minutes):
[Link] = hour
[Link] = minutes

def __add__(self, other):


total_minutes = [Link] * 60 + [Link] + [Link] * 60 +
[Link]
new_hour = total_minutes // 60
new_minutes = total_minutes % 60
return Time(new_hour, new_minutes)

def __str__(self):
return f"{[Link]:02d}:{[Link]:02d}"

def main():
time1 = Time(9, 30)
time2 = Time(1, 45)
print("Time 1:", time1)
print("Time 2:", time2)
print("Sum:", time1 + time2)
main()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------
Time 1: 09:30
Time 2: 01:45
Sum: 11:15
--------------------------------------------------------------------
Question 7 : Creating a Bank Account Class with Inheritance
● Define a base class Account with attributes like account_no
(string) and balance (float). Implement constructor method in
Account to initialize these attributes. • Create a subclass
BankAccount that inherits from Account.

● Add a method called deposit(amount) to BankAccount to add funds


to the balance.

● Optionally, you can add a withdraw(amount) method that subtracts


funds from the balance while considering overdraft protection (if
applicable).

--------------------------------------------------------------------
class Account:
def __init__(self, account_no, balance=0.0):
self.account_no = account_no
[Link] = balance

def display_balance(self):
print(f"Account Number: {self.account_no}, Balance: {[Link]}")

class BankAccount(Account):
def __init__(self, account_no, balance=0.0):
super().__init__(account_no, balance)

def deposit(self, amount):


[Link] += amount
print(f"Deposited {amount} into account {self.account_no}.")

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient funds!")
else:
[Link] -= amount
print(f"Withdrew {amount} from account {self.account_no}.")

bank_acc = BankAccount("123456789", 1000.0)


bank_acc.display_balance()
bank_acc.deposit(500.0)
bank_acc.display_balance()
bank_acc.withdraw(200.0)
bank_acc.display_balance()
--------------------------------------------------------------------
Output :
--------------------------------------------------------------------
Account Number: 123456789, Balance: 1000.0
Deposited 500.0 into account 123456789.
Account Number: 123456789, Balance: 1500.0
Withdrew 200.0 from account 123456789.
Account Number: 123456789, Balance: 1300.0
--------------------------------------------------------------------
Question 8 : Write a python program to create a CAR abstract class that
contains an instance variable, a concrete method and two abstract methods.
Also derive Maruti subclass from the CAR class and show implementation of
abstract methods of CAR in subclass.
from abc import ABC, abstractmethod.
--------------------------------------------------------------------
class Car(ABC):
def __init__(self, model):
[Link] = model

def display_model(self):
print("Model:", [Link])

@abstractmethod
def start(self):
pass

@abstractmethod
def stop(self):
pass

class Maruti(Car):
def start(self):
print("Maruti car started.")

def stop(self):
print("Maruti car stopped.")

# Creating an instance of Maruti class and calling methods


maruti_car = Maruti("Swift")
maruti_car.display_model()
maruti_car.start()
maruti_car.stop()

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

Model: Swift
Maruti car started.
Maruti car stopped.
--------------------------------------------------------------------
Question 9 : Create an interface Shape with methods area() and perimeter().
from abc import ABC, abstractmethod.
--------------------------------------------------------------------
class Shape:
def area(self):
pass

def perimeter(self):
pass

# Example implementation of Shape interface for a rectangle


class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

# Example usage
rectangle = Rectangle(5, 4)
print("Rectangle Area : ", [Link]())
print("Rectangle Perimeter : ", [Link]())

--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

Rectangle Area : 20
Rectangle Perimeter : 18
--------------------------------------------------------------------
Question 10 : Write a python program to handle the ZeroDivisionError
exception.
--------------------------------------------------------------------
def divide_numbers(x, y):
try:
result = x / y
print("Result of division : ", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

def get_user_input():
while True:
try:
x = float(input("Enter the numerator: "))
y = float(input("Enter the denominator: "))
return x, y
except ValueError:
print("Error: Please enter valid numerical values.")

# Main program
while True:
numerator, denominator = get_user_input()
divide_numbers(numerator, denominator)
continue_calculation = input("Do you want to continue (yes/no)? ").lower()
if continue_calculation != 'yes':
break
--------------------------------------------------------------------
Output :
--------------------------------------------------------------------

Enter the numerator: 10


Enter the denominator: 2
Result of division : 5.0
Do you want to continue (yes/no)? yes
Enter the numerator: 5
Enter the denominator: 0
Error: Division by zero is not allowed.
Do you want to continue (yes/no)? yes
Enter the numerator: 8
Enter the denominator: apex
Error: Please enter valid numerical values.
Enter the numerator: 20
Enter the denominator: 4
Result of division : 5.0
Do you want to continue (yes/no)? no

You might also like