You are on page 1of 31

\\ Write a Python program to create two empty classes, Student and Marks.

Now create some instances and check whether they are instances of the said classes or not.
Also, check whether the said classes are subclasses of the built-in object class or not.----------
ANS :- class Student:
pass
class Marks:
pass
student1 = Student()
marks1 = Marks()
print(isinstance(student1, Student))
print(isinstance(marks1, Student))
print(isinstance(marks1, Marks))
print(isinstance(student1, Marks))
print("\nCheck whether the said classes are subclasses of the built-in object class or not.")
print(issubclass(Student, object))
print(issubclass(Marks, object))
OUTPUT :- True
False
True
False
Check whether the said classes are subclasses of the built-in object class or not.
True
True

\\ Write a Python class named Student with two attributes student_name, marks.
Modify the attribute values of the said class and print the original and modified values of the said attribute
s.
ANS:-
class Student:
student_name = ’Terrance Morales’
marks = 93
print(f"Student Name: {getattr(Student, ’student_name’)}")
print(f"Marks: {getattr(Student, ’marks’)}")
setattr(Student, ’student_name’, ’Angel Brooks’)
setattr(Student, ’marks’, 95)
print(f"Student Name: {getattr(Student, ’student_name’)}")
print(f"Marks: {getattr(Student, ’marks’)}")
OUTPUT:- Student Name: Terrance Morales
Marks: 93
Student Name: Angel Brooks
Marks: 95

\\ Write a Python class named Student with two attributes student_id, student_name.
Add a new attribute student_class and display the entire attribute and the values of the class.
Now remove the student_name attribute and display the entire attribute with values.

ANS:- class Student:


student_id = ’V10’
student_name = ’Jacqueline Barnett’
print("Original attributes and their values of the Student class:")
for attr, value in Student._dict_.items():
if not attr.startswith(’_’):
print(f’{attr} -> {value}’)
print("\nAfter adding the student_class, attributes and their values with the said class:")
Student.student_class = ’V’
for attr, value in Student._dict_.items():
if not attr.startswith(’_’):
print(f’{attr} -> {value}’)
print("\nAfter removing the student_name, attributes and their values from the said class:")
del Student.student_name
#delattr(Student, ’student_name’)
for attr, value in Student._dict_.items():
if not attr.startswith(’_’):
print(f’{attr} -> {value}’)
OUTPUT:- Original attributes and their values of the Student class:
student_id -> V10
student_name -> Jacqueline Barnett

After adding the student_class, attributes and their values with the said class:
student_id -> V10
student_name -> Jacqueline Barnett
student_class -> V

After removing the student_name, attributes and their values from the said class:
student_id -> V10
student_class -> V

\\ Write a Python class Employee with attributes like emp_id, emp_name, emp_salary,
and emp_department and methods like calculate_emp_salary, emp_assign_department, and print_emplo
yee_details.

ANS:-
class Employee:
def __init__(self, name, emp_id, salary, department):
self.name = name
self.id = emp_id
self.salary = salary
self.department = department

def calculate_salary(self, salary, hours_worked):


overtime = 0
if hours_worked > 50:
overtime = hours_worked - 50
self.salary = self.salary + (overtime * (self.salary / 50))

def assign_department(self, emp_department):


self.department = emp_department
def print_employee_details(self):
print("\nName: ", self.name)
print("ID: ", self.id)
print("Salary: ", self.salary)
print("Department: ", self.department)
print("----------------------")

employee1 = Employee("ADAMS", "E7876", 50000, "ACCOUNTING")


employee2 = Employee("JONES", "E7499", 45000, "RESEARCH")
employee3 = Employee("MARTIN", "E7900", 50000, "SALES")
employee4 = Employee("SMITH", "E7698", 55000, "OPERATIONS")
print("Original Employee Details:")
employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()

# Change the departments of employee1 and employee4


employee1.assign_department("OPERATIONS")
employee4.assign_department("SALES")

# Now calculate the overtime of the employees who are eligible:


employee2.calculate_salary(45000, 52)
employee4.calculate_salary(45000, 60)

print("Updated Employee Details:")


employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()

OUTPUT:-
Original Employee Details:

Name: ADAMS
ID: E7876
Salary: 50000
Department: ACCOUNTING
----------------------

Name: JONES
ID: E7499
Salary: 45000
Department: RESEARCH
----------------------

Name: MARTIN
ID: E7900
Salary: 50000
Department: SALES
----------------------

Name: SMITH
ID: E7698
Salary: 55000
Department: OPERATIONS
----------------------
Updated Employee Details:

Name: ADAMS
ID: E7876
Salary: 50000
Department: OPERATIONS
----------------------

Name: JONES
ID: E7499
Salary: 46800.0
Department: RESEARCH
----------------------

Name: MARTIN
ID: E7900
Salary: 50000
Department: SALES
----------------------

Name: SMITH
ID: E7698
Salary: 66000.0
Department: SALES

\\ Write a Python class Restaurant with attributes like menu_items, book_table,


and customer_orders, and methods like add_item_to_menu, book_tables, and customer_order.

ANS:-
class Restaurant:
def __init__(self):
self.menu_items = {}
self.book_table = []
self.customer_orders = []

def add_item_to_menu(self, item, price):


self.menu_items[item] = price

def book_tables(self, table_number):


self.book_table.append(table_number)

def customer_order(self, table_number, order):


order_details = {’table_number’: table_number, ’order’: order}
self.customer_orders.append(order_details)

def print_menu_items(self):
for item, price in self.menu_items.items():
print("{}: {}".format(item, price))
def print_table_reservations(self):
for table in self.book_table:
print("Table {}".format(table))

def print_customer_orders(self):
for order in self.customer_orders:
print("Table {}: {}".format(order[’table_number’], order[’order’]))

restaurant = Restaurant()

# Add items
restaurant.add_item_to_menu("Cheeseburger", 9.99)
restaurant.add_item_to_menu("Caesar Salad", 8)
restaurant.add_item_to_menu("Grilled Salmon", 19.99)
restaurant.add_item_to_menu("French Fries", 3.99)
restaurant.add_item_to_menu("Fish & Chips:", 15)
# Book table
restaurant.book_tables(1)
restaurant.book_tables(2)
restaurant.book_tables(3)
# Order items
restaurant.customer_order(1, "Cheeseburger")
restaurant.customer_order(1, "Grilled Salmon")
restaurant.customer_order(2, "Fish & Chips")
restaurant.customer_order(2, "Grilled Salmon")

print("\nPopular dishes in the restaurant along with their prices:")


restaurant.print_menu_items()
print("\nTable reserved in the Restaurant:")
restaurant.print_table_reservations()
print("\nPrint customer orders:")
restaurant.print_customer_orders()

OUTPUT:-
Popular dishes in the restaurant along with their prices:
Cheeseburger: 9.99
Caesar Salad: 8
Grilled Salmon: 19.99
French Fries: 3.99
Fish & Chips:: 15

Table reserved in the Restaurant:


Table 1
Table 2
Table 3

Print customer orders:


Table 1: Cheeseburger
Table 1: Grilled Salmon
Table 2: Fish & Chips
Table 2: Grilled Salmon

\\ Write a Python class Restaurant with attributes like menu_items,


book_table, and customer_orders, and methods like add_item_to_menu, book_tables, and customer_ord
er.
Perform the following tasks now:
Now add items to the menu.
Make table reservations.
Take customer orders.
Print the menu.
Print table reservations.
Print customer orders.

ANS:-
class Restaurant:
def __init__(self):
self.menu_items = {}
self.book_table = []
self.customer_orders = []
def add_item_to_menu(self, item, price):
self.menu_items[item] = price
def book_tables(self, table_number):
self.book_table.append(table_number)
def customer_order(self, table_number, order):
order_details = {’table_number’: table_number, ’order’: order}
self.customer_orders.append(order_details)
def print_menu_items(self):
for item, price in self.menu_items.items():
print("{}: {}".format(item, price))
def print_table_reservations(self):
for table in self.book_table:
print("Table {}".format(table))
def print_customer_orders(self):
for order in self.customer_orders:
print("Table {}: {}".format(order[’table_number’], order[’order’]))
restaurant = Restaurant()
# Add items
restaurant.add_item_to_menu("Cheeseburger", 9.99)
restaurant.add_item_to_menu("Caesar Salad", 8)
restaurant.add_item_to_menu("Grilled Salmon", 19.99)
restaurant.add_item_to_menu("French Fries", 3.99)
restaurant.add_item_to_menu("Fish & Chips:", 15)
# Book table
restaurant.book_tables(1)
restaurant.book_tables(2)
restaurant.book_tables(3)
# Order items
restaurant.customer_order(1, "Cheeseburger")
restaurant.customer_order(1, "Grilled Salmon")
restaurant.customer_order(2, "Fish & Chips")
restaurant.customer_order(2, "Grilled Salmon")

print("\nPopular dishes in the restaurant along with their prices:")


restaurant.print_menu_items()
print("\nTable reserved in the Restaurant:")
restaurant.print_table_reservations()
print("\nPrint customer orders:")
restaurant.print_customer_orders()

OUTPUT:-
Popular dishes in the restaurant along with their prices:
Cheeseburger: 9.99
Caesar Salad: 8
Grilled Salmon: 19.99
French Fries: 3.99
Fish & Chips:: 15
Table reserved in the Restaurant:
Table 1
Table 2
Table 3
Print customer orders:
Table 1: Cheeseburger
Table 1: Grilled Salmon
Table 2: Fish & Chips
Table 2: Grilled Salmon
\\ Write a Python class Inventory with attributes like item_id, item_name,
stock_count, and price, and methods like add_item, update_item, and check_item_details.

Use a dictionary to store the item details,


where the key is the item_id and the value is a dictionary containing the item_name, stock_count, and pri
ce

ANS:-
class Inventory:
def __init__(self):
self.inventory = {}
def add_item(self, item_id, item_name, stock_count, price):
self.inventory[item_id] = {"item_name": item_name, "stock_count": stock_count, "price": price}
def update_item(self, item_id, stock_count, price):
if item_id in self.inventory:
self.inventory[item_id]["stock_count"] = stock_count
self.inventory[item_id]["price"] = price
else:
print("Item not found in inventory.")
def check_item_details(self, item_id):
if item_id in self.inventory:
item = self.inventory[item_id]
return f"Product Name: {item[’item_name’]}, Stock Count: {item[’stock_count’]}, Price: {item[’price’]
}"
else:
return "Item not found in inventory."
inventory = Inventory()
inventory.add_item("I001", "Laptop", 100, 500.00)
inventory.add_item("I002", "Mobile", 110, 450.00)
inventory.add_item("I003", "Desktop", 120, 500.00)
inventory.add_item("I004", "Tablet", 90, 550.00)
print("Item Details:")
print(inventory.check_item_details("I001"))
print(inventory.check_item_details("I002"))
print(inventory.check_item_details("I003"))
print(inventory.check_item_details("I004"))
print("\nUpdate the price of item code - ’I001’:")
inventory.update_item("I001", 100, 505.00)
print(inventory.check_item_details("I001"))
print("\nUpdate the stock of item code - ’I003’:")
inventory.update_item("I003", 115, 500.00)
print(inventory.check_item_details("I003"))

OUTPUT:-
Item Details:
Product Name: Laptop, Stock Count: 100, Price: 500.0
Product Name: Mobile, Stock Count: 110, Price: 450.0
Product Name: Desktop, Stock Count: 120, Price: 500.0
Product Name: Tablet, Stock Count: 90, Price: 550.0
Update the price of item code - ’I001’:
Product Name: Laptop, Stock Count: 100, Price: 505.0
Update the stock of item code - ’I003’:
Product Name: Desktop, Stock Count: 115, Price: 500.0

\\ Write a Python class BankAccount with attributes like account_number, balance,


date_of_opening and customer_name, and methods like deposit, withdraw, and check_balance.

ANS:-
class BankAccount:
def __init__(self, account_number, date_of_opening, balance, customer_name):
self.account_number = account_number
self.date_of_opening = date_of_opening
self.balance = balance
self.customer_name = customer_name
def deposit(self, amount):
self.balance += amount
print(f"${amount} has been deposited in your account.")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance.")
else:
self.balance -= amount
print(f"${amount} has been withdrawn from your account.")
def check_balance(self):
print(f"Current balance is ${self.balance}.")
def print_customer_details(self):
print("Name:", self.customer_name)
print("Account Number:", self.account_number)
print("Date of opening:", self.date_of_opening)
print(f"Balance: ${self.balance}\n")
# Input customer details
ac_no_1 = BankAccount(2345, "01-01-2011", 1000, "Toninho Takeo")
ac_no_2 = BankAccount(1234, "11-03-2011", 2000, "Astrid Rugile")
ac_no_3 = BankAccount(2312, "12-01-2009", 3000, "Orli Kerenza")
ac_no_4 = BankAccount(1395, "01-01-2011", 3000, "Luciana Chika")
ac_no_5 = BankAccount(6345, "01-05-2011", 4000, "Toninho Takeo")
print("Customer Details:")
ac_no_1.print_customer_details()
ac_no_2.print_customer_details()
ac_no_3.print_customer_details()
ac_no_4.print_customer_details()
ac_no_5.print_customer_details()
print("=============================")
ac_no_4.print_customer_details()
# Current balance is $3000.
# $1000 has been deposited in your account.
ac_no_4.deposit(1000)
ac_no_4.check_balance()
# Your current balance $4000.
# You want to withdraw $5000
ac_no_4.withdraw(5000)
# Output:
# Insufficient balance.
#The customer withdraw $3400.
ac_no_4.withdraw(3400)
ac_no_4.check_balance()

OUTPUT:-
Customer Details:
Name: Toninho Takeo
Account Number: 2345
Date of opening: 01-01-2011
Balance: $1000
Name: Astrid Rugile
Account Number: 1234
Date of opening: 11-03-2011
Balance: $2000
Name: Orli Kerenza
Account Number: 2312
Date of opening: 12-01-2009
Balance: $3000
Name: Luciana Chika
Account Number: 1395
Date of opening: 01-01-2011
Balance: $3000
Name: Toninho Takeo
Account Number: 6345
Date of opening: 01-05-2011
Balance: $4000
=============================
Name: Luciana Chika
Account Number: 1395
Date of opening: 01-01-2011
Balance: $3000
$1000 has been deposited in your account.
Current balance is $4000.
Insufficient balance.
$3400 has been withdrawn from your account.
Current balance is $600.

\\ Write a Python class Employee with attributes like emp_id,


emp_name, emp_salary, and emp_department and methods like calculate_emp_salary,
emp_assign_department, and print_employee_details.
Sample Employee Data:
"ADAMS", "E7876", 50000, "ACCOUNTING"
"JONES", "E7499", 45000, "RESEARCH"
"MARTIN", "E7900", 50000, "SALES"
"SMITH", "E7698", 55000, "OPERATIONS"
Use ’assign_department’ method to change the department of an employee.
Use ’print_employee_details’ method to print the details of an employee.
Use ’calculate_emp_salary’ method takes two arguments: salary and hours_worked, which is the number
of hours worked by the employee. If the number of hours worked is more than 50, the method computes o
vertime and adds it to the salary. Overtime is calculated as following formula:
overtime = hours_worked – 50
Overtime amount = (overtime * (salary / 50))

ANS:-
class Employee:
def __init__(self, name, emp_id, salary, department):
self.name = name
self.id = emp_id
self.salary = salary
self.department = department

def calculate_salary(self, salary, hours_worked):


overtime = 0
if hours_worked > 50:
overtime = hours_worked - 50
self.salary = self.salary + (overtime * (self.salary / 50))

def assign_department(self, emp_department):


self.department = emp_department

def print_employee_details(self):
print("\nName: ", self.name)
print("ID: ", self.id)
print("Salary: ", self.salary)
print("Department: ", self.department)
print("----------------------")

employee1 = Employee("ADAMS", "E7876", 50000, "ACCOUNTING")


employee2 = Employee("JONES", "E7499", 45000, "RESEARCH")
employee3 = Employee("MARTIN", "E7900", 50000, "SALES")
employee4 = Employee("SMITH", "E7698", 55000, "OPERATIONS")
print("Original Employee Details:")
employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()
# Change the departments of employee1 and employee4
employee1.assign_department("OPERATIONS")
employee4.assign_department("SALES")
# Now calculate the overtime of the employees who are eligible:
employee2.calculate_salary(45000, 52)
employee4.calculate_salary(45000, 60)
print("Updated Employee Details:")
employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()

OUTPUT:-
Original Employee Details:
Name: ADAMS
ID: E7876
Salary: 50000
Department: ACCOUNTING
----------------------
Name: JONES
ID: E7499
Salary: 45000
Department: RESEARCH
----------------------
Name: MARTIN
ID: E7900
Salary: 50000
Department: SALES
----------------------
Name: SMITH
ID: E7698
Salary: 55000
Department: OPERATIONS
----------------------
Updated Employee Details:
Name: ADAMS
ID: E7876
Salary: 50000
Department: OPERATIONS
----------------------
Name: JONES
ID: E7499
Salary: 46800.0
Department: RESEARCH
----------------------
Name: MARTIN
ID: E7900
Salary: 50000
Department: SALES
----------------------
Name: SMITH
ID: E7698
Salary: 66000.0
Department: SALES
----------------------

\\ Write a Python program to create a class representing a shopping cart.


Include methods for adding and removing items, and calculating the total price

ANS:=
class ShoppingCart:
# Initialize the shopping cart with an empty list of items
def __init__(self):
self.items = []
# Add an item with a name and quantity to the shopping cart
def add_item(self, item_name, qty):
item = (item_name, qty)
self.items.append(item)
# Remove an item with a specific name from the shopping cart
def remove_item(self, item_name):
for item in self.items:
if item[0] == item_name:
self.items.remove(item)
break
# Calculate and return the total quantity of items in the shopping cart
def calculate_total(self):
total = 0
for item in self.items:
total += item[1]
return total
# Example usage
# Create an instance of the ShoppingCart class
cart = ShoppingCart()
# Add items to the shopping cart
cart.add_item("Papaya", 100)
cart.add_item("Guava", 200)
cart.add_item("Orange", 150)
# Display the current items in the cart and calculate the total quantity
print("Current Items in Cart:")
for item in cart.items:
print(item[0], "-", item[1])
total_qty = cart.calculate_total()
print("Total Quantity:", total_qty)
# Remove an item from the cart, display the updated items, and recalculate the total quantity
cart.remove_item("Orange")
print("\nUpdated Items in Cart after removing Orange:")
for item in cart.items:
print(item[0], "-", item[1])
total_qty = cart.calculate_total()
print("Total Quantity:", total_qty)

OUTPUT:=
Current Items in Cart:
Papaya - 100
Guava - 200
Orange - 150
Total Quantity: 450
Updated Items in Cart after removing Orange:
Papaya - 100
Guava - 200
Total Quantity: 300

\\ Write a Python program to create a class representing a bank.


Include methods for managing customer accounts and transactions.

ANS:=
class Bank:
# Initialize the bank with an empty dictionary to store customer accounts and balances
def __init__(self):
self.customers = {}
# Create a new account with a given account number and an optional initial balance (default to 0)
def create_account(self, account_number, initial_balance=0):
if account_number in self.customers:
print("Account number already exists.")
else:
self.customers[account_number] = initial_balance
print("Account created successfully.")
# Make a deposit to the account with the given account number
def make_deposit(self, account_number, amount):
if account_number in self.customers:
self.customers[account_number] += amount
print("Deposit successful.")
else:
print("Account number does not exist.")
# Make a withdrawal from the account with the given account number
def make_withdrawal(self, account_number, amount):
if account_number in self.customers:
if self.customers[account_number] >= amount:
self.customers[account_number] -= amount
print("Withdrawal successful.")
else:
print("Insufficient funds.")
else:
print("Account number does not exist.")
# Check and print the balance of the account with the given account number
def check_balance(self, account_number):
if account_number in self.customers:
balance = self.customers[account_number]
print(f"Account balance: {balance}")
else:
print("Account number does not exist.")
# Example usage
# Create an instance of the Bank class
bank = Bank()
# Create customer accounts and perform account operations
acno1= "SB-123"
damt1 = 1000
print("New a/c No.: ",acno1,"Deposit Amount:",damt1)
bank.create_account(acno1, damt1)
acno2= "SB-124"
damt2 = 1500
print("New a/c No.: ",acno2,"Deposit Amount:",damt2)
bank.create_account(acno2, damt2)
wamt1 = 600
print("\nDeposit Rs.",wamt1,"to A/c No.",acno1)
bank.make_deposit(acno1, wamt1)
wamt2 = 350
print("Withdraw Rs.",wamt2,"From A/c No.",acno2)
bank.make_withdrawal(acno2, wamt2)
print("A/c. No.",acno1)
bank.check_balance(acno1)
print("A/c. No.",acno2)
bank.check_balance(acno2)
wamt3 = 1200
print("Withdraw Rs.",wamt3,"From A/c No.",acno2)
bank.make_withdrawal(acno2, wamt3)
acno3 = "SB-134"
print("A/c. No.",acno3)
bank.check_balance(acno3) # Non-existent account number

OUTPUT:=
New a/c No.: SB-123 Deposit Amount: 1000
Account created successfully.
New a/c No.: SB-124 Deposit Amount: 1500
Account created successfully.
Deposit Rs. 600 to A/c No. SB-123
Deposit successful.
Withdraw Rs. 350 From A/c No. SB-124
Withdrawal successful.
A/c. No. SB-123
Account balance: 1600
A/c. No. SB-124
Account balance: 1150
Withdraw Rs. 1200 From A/c No. SB-124
Insufficient funds.
A/c. No. SB-134
Account number does not exist.

\\ Write a Python program to create a class that represents a shape.


Include methods to calculate its area and perimeter.
Implement subclasses for different shapes like circle, triangle, and square.

ANS:=
import math

# Define a base class called Shape to represent a generic shape with methods for calculating area and p
erimeter
class Shape:
# Placeholder method for calculating area (to be implemented in derived classes)
def calculate_area(self):
pass
# Placeholder method for calculating perimeter (to be implemented in derived classes)
def calculate_perimeter(self):
pass
# Define a derived class called Circle, which inherits from the Shape class
class Circle(Shape):
# Initialize the Circle object with a given radius
def __init__(self, radius):
self.radius = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_area(self):
return math.pi * self.radius**2
# Calculate and return the perimeter of the circle using the formula: 2π * r
def calculate_perimeter(self):
return 2 * math.pi * self.radius
# Define a derived class called Rectangle, which inherits from the Shape class
class Rectangle(Shape):
# Initialize the Rectangle object with given length and width
def __init__(self, length, width):
self.length = length
self.width = width
# Calculate and return the area of the rectangle using the formula: length * width
def calculate_area(self):
return self.length * self.width
# Calculate and return the perimeter of the rectangle using the formula: 2 * (length + width)
def calculate_perimeter(self):
return 2 * (self.length + self.width)
class Triangle(Shape):
# Initialize the Triangle object with a base, height, and three side lengths
def __init__(self, base, height, side1, side2, side3):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
self.side3 = side3

# Calculate and return the area of the triangle using the formula: 0.5 * base * height
def calculate_area(self):
return 0.5 * self.base * self.height
# Calculate and return the perimeter of the triangle by adding the lengths of its three sides
def calculate_perimeter(self):
return self.side1 + self.side2 + self.side3
# Example usage
# Create a Circle object with a given radius and calculate its area and perimeter
r=7
circle = Circle(r)
circle_area = circle.calculate_area()
circle_perimeter = circle.calculate_perimeter()
# Print the results for the Circle
print("Radius of the circle:", r)
print("Circle Area:", circle_area)
print("Circle Perimeter:", circle_perimeter)
# Create a Rectangle object with given length and width and calculate its area and perimeter
l=5
w=7
rectangle = Rectangle(l, w)
rectangle_area = rectangle.calculate_area()
rectangle_perimeter = rectangle.calculate_perimeter()
# Print the results for the Rectangle
print("\nRectangle: Length =", l, " Width =", w)
print("Rectangle Area:", rectangle_area)
print("Rectangle Perimeter:", rectangle_perimeter)
# Create a Triangle object with a base, height, and three side lengths, and calculate its area and perimete
r
base = 5
height = 4
s1 = 4
s2 = 3
s3 = 5
# Print the results for the Triangle
print("\nTriangle: Base =", base, " Height =", height, " side1 =", s1, " side2 =", s2, " side3 =", s3)
triangle = Triangle(base, height, s1, s2, s3)
triangle_area = triangle.calculate_area()
triangle_perimeter = triangle.calculate_perimeter()
print("Triangle Area:", triangle_area)
print("Triangle Perimeter:", triangle_perimeter)

OUTPUT:=
Radius of the circle: 7
Circle Area: 153.93804002589985
Circle Perimeter: 43.982297150257104
Rectangle: Length = 5 Width = 7
Rectangle Area: 35
Rectangle Perimeter: 24
Triangle: Base = 5 Height = 4 side1 = 4 side2 = 3 side3 = 5
Triangle Area: 10.0
Triangle Perimeter: 12

\\ THE CONTAINER CLASS WAS IMPLIMENTED *PLASTICVOTAINER *METALCONTAINER

ANS:=
class Container:
pass
class PlasticContainer(Container):
pass
class MetalContainer(Container):
pass
class CustomeContainer():
pass
print(issubclass(PlasticContainer,Container))
print(issubclass(MetalContainer,Container))
print(issubclass(CustomeContainer,Container))

OUTPUT:=
True
True
False

\\ THE FOLLO CLAS IMP *VEHICAL*LANDVEHICAL*AIRVEHICAL


ANS:=
class Vehicle:
def __init__(self,category=None):
self.category=category if category else "Vihicle"
def display(self):
print(f"{self.__class__.__name__} ({self.category})")
class landvihicle(Vehicle):
def __init__(self,category=None):
self.category=category if category else "Land Vihicle"
class Airvihicle(Vehicle):
def __init__(self,category=None):
self.category=category if category else "Air Vihicle"
v=[Vehicle(),landvihicle(),Airvihicle()]
for i in v:
i.display()

OUTPUT:=
Vehicle (Vihicle)
landvihicle (Land Vihicle)
Airvihicle (Air Vihicle)

\\ THE FOLOW IMP *VEHICAL*LANDVEHICAL*AIRVEHICAL define a disply info ,method in class name
along
with the value of catorogy attribute
ANS:=

class Vihicle:
def __init__(self,category=None):
self.category=category if category else "Vihicle"
def __str__(self):
return f"Vical"
def __repr__(self):
return f"{self.__class__.__name__},({self.category})"
class land_vihical(Vihicle):
def __init__(self,category=None):
self.category=category if category else "Land Vihicle"
class Air_vihical(Vihicle):
def __init__(self,category=None):
self.category=category if category else "Air Vihicle"
v=[Vihicle(),land_vihical(),Air_vihical()]
for i in v:
print(repr(i))
OUTPUT:=
Vihicle,(Vihicle)
land_vihical,(Land Vihicle)
Air_vihical,(Air Vihicle)

\\ A VEHICAL CLASS IS GIVEN THAT HAS 3 INSTANCE ATTRIBUTES

ANS:=
class Vehicle:
def __init__(self,brand,color,year):
self.brand=brand
self.color=color
self.year=year
class Car(Vehicle):
def __init__(self,brand,color,year,horsepower):
self.brand=brand
self.color=color
self.year=year
self.horsepower=horsepower
v=Vehicle('BMW','Red',2020)
print(v.__dict__)
c=Car('BMW','Red',2020,300)
print(c.__dict__)

OUTPUT:=
{'brand': 'BMW', 'color': 'Red', 'year': 2020}
{'brand': 'BMW', 'color': 'Red', 'year': 2020, 'horsepower': 300}

\\ Write a Python program to create a class that represents a shape.


Include methods to calculate its area and perimeter. Implement subclasses for different shapes like circle,

triangle, and square

ANS:=
import math
# Define a base class called Shape to represent a generic shape with methods for calculating area and pe
rimeter
class Shape:
# Placeholder method for calculating area (to be implemented in derived classes)
def calculate_area(self):
pass
# Placeholder method for calculating perimeter (to be implemented in derived classes)
def calculate_perimeter(self):
pass
# Define a derived class called Circle, which inherits from the Shape class
class Circle(Shape):
# Initialize the Circle object with a given radius
def __init__(self, radius):
self.radius = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_area(self):
return math.pi * self.radius**2
# Calculate and return the perimeter of the circle using the formula: 2π * r
def calculate_perimeter(self):
return 2 * math.pi * self.radius
# Define a derived class called Rectangle, which inherits from the Shape class
class Rectangle(Shape):
# Initialize the Rectangle object with given length and width
def __init__(self, length, width):
self.length = length
self.width = width
# Calculate and return the area of the rectangle using the formula: length * width
def calculate_area(self):
return self.length * self.width
# Calculate and return the perimeter of the rectangle using the formula: 2 * (length + width)
def calculate_perimeter(self):
return 2 * (self.length + self.width)
# Define a derived class called Triangle, which inherits from the Shape class
class Triangle(Shape):
# Initialize the Triangle object with a base, height, and three side lengths
def __init__(self, base, height, side1, side2, side3):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
self.side3 = side3
# Calculate and return the area of the triangle using the formula: 0.5 * base * height
def calculate_area(self):
return 0.5 * self.base * self.height
# Calculate and return the perimeter of the triangle by adding the lengths of its three sides
def calculate_perimeter(self):
return self.side1 + self.side2 + self.side3
# Example usage
# Create a Circle object with a given radius and calculate its area and perimeter
r=7
circle = Circle(r)
circle_area = circle.calculate_area()
circle_perimeter = circle.calculate_perimeter()
# Print the results for the Circle
print("Radius of the circle:", r)
print("Circle Area:", circle_area)
print("Circle Perimeter:", circle_perimeter)
# Create a Rectangle object with given length and width and calculate its area and perimeter
l=5
w=7
rectangle = Rectangle(l, w)
rectangle_area = rectangle.calculate_area()
rectangle_perimeter = rectangle.calculate_perimeter()
# Print the results for the Rectangle
print("\nRectangle: Length =", l, " Width =", w)
print("Rectangle Area:", rectangle_area)
print("Rectangle Perimeter:", rectangle_perimeter)
# Create a Triangle object with a base, height, and three side lengths, and calculate its area and perimete
r
base = 5
height = 4
s1 = 4
s2 = 3
s3 = 5
# Print the results for the Triangle
print("\nTriangle: Base =", base, " Height =", height, " side1 =", s1, " side2 =", s2, " side3 =", s3)
triangle = Triangle(base, height, s1, s2, s3)
triangle_area = triangle.calculate_area()
triangle_perimeter = triangle.calculate_perimeter()
print("Triangle Area:", triangle_area)
print("Triangle Perimeter:", triangle_perimeter)

OUTPUT:=
Radius of the circle: 7
Circle Area: 153.93804002589985
Circle Perimeter: 43.982297150257104
Rectangle: Length = 5 Width = 7
Rectangle Area: 35
Rectangle Perimeter: 24
Triangle: Base = 5 Height = 4 side1 = 4 side2 = 3 side3 = 5
Triangle Area: 10.0
Triangle Perimeter: 12

\\ CAPICITY SPEED

ANS:=
class vehicle:
def __init__(self,capacity,speed):
self.capacity=capacity
self.speed=speed
def showCapacity():
pass
def showSpeed():
pass
class car:
def __init__(self,capacity,speed):
super().__init__(self,capacity,speed)
def showCapacity():
return f"capacity of {self.__class__.__name__} is {self.capacity}"
def showSpeed():
return f"speed of {self.__class__.__name__} is {self.speed}"
class truck:
def __init__(self,capacity,speed):
super().__init__(self,capacity,speed)
def showCapacity():
return f"capacity of {self.__class__.__name__} is {self.capacity}"
def showSpeed():
return f"speed of {self.__class__.__name__} is {self.speed} "

\\ create an abstrtact class named Taxpayer

ANS:=
def convert_data_type(data_type):
def decorator(func):
def wrapper(*args,**kwargs):
result=func(*args,**kwargs)
return data_type(result)
return wrapper
return decorator
@convert_data_type(int)
def add(x,y):
return x+y
result=add(4,6)
print(f"result ={result} type ={type(result)}")

@convert_data_type(str)
def concatenate_string(x,y):
return x+y
result=concatenate_string("jay","deep")
print(f"result ={result} type ={type(result)}")

OUTPUT:=
result =10 type =<class 'int'>
result =jaydeep type =<class 'str'>

\\ An implementation of the Taxpayer abstract class is given. Create a class derived from Taxpayer name
d Student
Tax Payer that implements the caicuiate tax() method that calculates the 15% salary tax (salary
attribute) Then create an instance of the Student Tax Payer class named student and salary 40,000.
In response, by calling caicuiate_tax() print the calculated tax to the console.

ANS:=
def cache_result(func):
cache = {}
def wrapper(*args, **kwargs):
key = (*args, *kwargs.items())
print(key)

if key in cache:
print("Retrieving result from cache...")
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
return result
return wrapper
# Example usage
@cache_result
def calculate_multiply(x, y):
print("Calculating the product of two numbers...")
return x * y
# Call the decorated function multiple times
print(calculate_multiply(4, 5))
print(calculate_multiply(4,5))
print(calculate_multiply(4,6))

OUTPUT:=
(4, 5)
Calculating the product of two numbers...
20
(4, 5)
Retrieving result from cache...
20
(4, 6)
Calculating the product of two numbers...
24

\\ Write a Python program that creates a generator function that yields cubes of numbers from 1 to n.
Accept n from the user.

ANS:=
def cube_generator(n):
for i in range(1, n + 1):
yield i ** 3
# Accept input from the user
n = int(input("Input a number: "))
# Create the generator object
cubes = cube_generator(n)
# Iterate over the generator and print the cubes
print("Cubes of numbers from 1 to", n)
for num in cubes:
print(num)

OUTPUT:=
Input a number: 10
Cubes of numbers from 1 to 10
1
8
27
64
125
216
343
512
729
1000

\\ Write a Python program to implement a generator that generates random numbers within a given range.

ANS:=
import random

def random_number_generator(start, end):


while True:
yield random.randint(start, end)
# Accept input from the user
start = int(input("Input the start value: "))
end = int(input("Input the end value: "))
# Create the generator object
random_numbers = random_number_generator(start, end)
# Generate and print 10 random numbers
print("Random numbers between",start,"and",end)
for _ in range(10):
print(next(random_numbers))

OUTPUT:=
Input the start value: 1
Input the end value: 10
Random numbers between 1 and 10
10
6
4
6
6
5
6
2
8
9

Input the start value: 445


Input the end value: 760
Random numbers between 445 and 760
489
687
611
695
731
455
504
567
704
468

\\ Write a Python program that creates a generator function that generates all prime numbers
between two given numbers.

ANS:=
def is_prime_num(n):
# Check if the number is prime
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def prime_numbers(start, end):
# Generate prime numbers between start and end
for num in range(start, end + 1):
if is_prime_num(num):
yield num
# Accept input from the user
start = int(input("Input the starting number: "))
end = int(input("Input the ending number: "))
# Create the prime numbers generator
prime_gen = prime_numbers(start, end)
# Generate and print all prime numbers
print("Prime numbers between", start, "and", end, "are:")
for prime in prime_gen:
print(prime, end=",")

OUTPUT:=
Input the starting number: 1
Input the ending number: 30
Prime numbers between 1 and 30 are:
2,3,5,7,11,13,17,19,23,29,

Input the starting number: 100


Input the ending number: 200
Prime numbers between 100 and 200 are:
101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,

\\ Write a Python program to implement a generator function that generates the Fibonacci sequence.

ANS:=
def fibonacci():
x, y = 0, 1
while True:
yield x
x, y = y, x + y

# Accept input from the user


n = int(input("Input the number of Fibonacci numbers you want to generate? "))

print("Number of first ",n,"Fibonacci numbers:")


fib = fibonacci()
for _ in range(n):
print(next(fib),end=" ")

OUTPUT:=
Input the number of Fibonacci numbers you want to generate? 4
Number of first 4 Fibonacci numbers:
0112

Input the number of Fibonacci numbers you want to generate? 10


Number of first 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34

\\ Write a Python program to make an iterator that drops elements from the iterable
as long as the elements are negative; afterwards, it returns every element.

ANS:=
import itertools as it
def drop_while(nums):
return it.takewhile(lambda x : x < 0, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print("Original list: ",nums)
result = drop_while(nums)
print("Drop elements from the said list as long as the elements are negative\n",list(result))
#Alternate solution
def negative_num(x):
return x < 0
def drop_while(nums):
return it.dropwhile(negative_num, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print("Original list: ",nums)
result = drop_while(nums)
print("Drop elements from the said list as long as the elements are negative\n",list(result))
OUTPUT:=
Original list: [-1, -2, -3, 4, -10, 2, 0, 5, 12]
Drop elements from the said list as long as the elements are negative
[-1, -2, -3]
Original list: [-1, -2, -3, 4, -10, 2, 0, 5, 12]
Drop elements from the said list as long as the elements are negative
[4, -10, 2, 0, 5, 12]

\\ Write a Python program to make an iterator that drops


elements from the iterable as soon as an element is a positive number.
ANS:=
import itertools as it
def drop_while(nums):
return it.dropwhile(lambda x : x < 0, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print("Original list: ",nums)
result = drop_while(nums)
print("Drops elements from the iterable when a positive number arises \n",list(result))
#Alternate solution
def negative_num(x):
return x < 0
def drop_while(nums):
return it.dropwhile(negative_num, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print("Original list: ",nums)
result = drop_while(nums)
print("Drops elements from the iterable when a positive number arises \n",list(result))

OUTPUT:=
Original list: [-1, -2, -3, 4, -10, 2, 0, 5, 12]
Drops elements from the iterable when a positive number arises
[4, -10, 2, 0, 5, 12]
Original list: [-1, -2, -3, 4, -10, 2, 0, 5, 12]
Drops elements from the iterable when a positive number arises
[4, -10, 2, 0, 5, 12]

\\ Write a Python program to generate an infinite cycle of elements from an iterable.

ANS:=
import itertools as it
def cycle_data(iter):
return it.cycle(iter)
# Following loops will run for ever
#List
result = cycle_data(['A','B','C','D'])
print("The said function print never-ending items:")
for i in result:
print(i)
#String
result = cycle_data('Python itertools')
print("The said function print never-ending items:")
for i in result:
print(i)

OUTPUT:=
The said function print never-ending items:
A
B
C
D
A
B
C
D
A
B
C
D
A
B
C
D
A
B
....

\\ Write a Python program to create an iterator from several iterables in a sequence


and display the type and elements of the new iterator.

ANS:=
from itertools import chain
def chain_func(l1,l2,l3):
return chain(l1,l2,l3)
#List
result = chain_func([1,2,3], ['a','b','c','d'], [4,5,6,7,8,9])
print("Type of the new iterator:")
print(type(result))
print("Elements of the new iterator:")
for i in result:
print(i)
#Tuple
result = chain_func((10,20,30,40), ('A','B','C','D'), (40,50,60,70,80,90))
print("Type of the new iterator:")
print(type(result))
print("Elements of the new iterator:")
for i in result:
print(i)

OUTPUT:=
Type of the new iterator:
<class 'itertools.chain'>
Elements of the new iterator:
1
2
3
a
b
c
d
4
5
6
7
8
9
Type of the new iterator:
<class 'itertools.chain'>
Elements of the new iterator:
10
20
30
40
A
B
C
D
40
50
60
70
80
90

\\ Write a Python program that generates the running product of elements in an iterable

ANS:=
from itertools import accumulate
import operator
def running_product(it):
return accumulate(it,operator.mul)
#List
result = running_product([1,2,3,4,5,6,7])
print("Running product of a list:")
for i in result:
print(i)
#Tuple
result = running_product((1,2,3,4,5,6,7))
print("Running product of a Tuple:")
for i in result:
print(i)

OUTPUT:=
Type of the new iterator:
<class 'itertools.chain'>
Running product of a list:
1
2
6
24
120
720
5040
Running product of a Tuple:
1
2
6
24
120
720
5040

\\ Write a Python program to generate the maximum and minimum values of the elements of an iterable.

ANS:=
from itertools import accumulate
def running_max_product(iters):
return accumulate(iters, max)
#List
result = running_max_product([1,3,2,7,9,8,10,11,12,14,11,12,7])
print("Running maximum value of a list:")
for i in result:
print(i)
#Tuple
result = running_max_product((1,3,3,7,9,8,10,9,8,14,11,15,7))
print("Running maximum value of a Tuple:")
for i in result:
print(i)
def running_min_product(iters):
return accumulate(iters, min)
#List
result = running_min_product([3,2,7,9,8,10,11,12,1,14,11,12,7])
print("Running minimum value of a list:")
for i in result:
print(i)
#Tuple
result = running_min_product((1,3,3,7,9,8,10,9,8,0,11,15,7))
print("Running minimum value of a Tuple:")
for i in result:
print(i)

OUTPUT:=
Running maximum value of a list:
1
3
3
7
9
9
10
11
12
14
14
14
14
Running maximum value of a Tuple:
1
3
3
7
9
9
10
10
10
14
14
15
15
Running minimum value of a list:
3
2
2
2
2
2
2
2
1
1
1
1
1
Running minimum value of a Tuple:
1
1
1
1
1
1
1
1
1
0
0
0
0

\\ Write a Python program to sum all the items in a list.

ANS:=
# Define a function called sum_list that takes a list 'items' as input
def sum_list(items):
# Initialize a variable 'sum_numbers' to store the sum of the numbers
sum_numbers = 0
# Iterate through each element 'x' in the input list 'items'
for x in items:
# Add the current element 'x' to the 'sum_numbers' variable
sum_numbers += x
# Return the final sum of the numbers
return sum_numbers

# Call the sum_list function with the list [1, 2, -8] as input and print the result
print(sum_list([1, 2, -8]))
OUTPUT:=
-5

\\ Write a Python program to multiply all the items in a list.

ANS:=
# Define a function called multiply_list that takes a list 'items' as input
def multiply_list(items):
# Initialize a variable 'tot' to store the product of the numbers, starting with 1
tot = 1
# Iterate through each element 'x' in the input list 'items'
for x in items:
# Multiply the current element 'x' with the 'tot' variable
tot *= x
# Return the final product of the numbers
return tot
# Call the multiply_list function with the list [1, 2, -8] as input and print the result
print(multiply_list([1, 2, -8]))

OUTPUT:=
-16

\\ Write a Python program to get the largest number from a list.

ANS:=
# Define a function called max_num_in_list that takes a list 'list' as input
def max_num_in_list(list):
# Initialize a variable 'max' with the first element of the input list as the initial maximum
max = list[0]
# Iterate through each element 'a' in the input list 'list'
for a in list:
# Check if the current element 'a' is greater than the current maximum 'max'
if a > max:
# If 'a' is greater, update the maximum 'max' to 'a'
max = a
# Return the final maximum value in the list
return max
# Call the max_num_in_list function with the list [1, 2, -8, 0] as input and print the result
print(max_num_in_list([1, 2, -8, 0]))

OUTPUT:=
2

\\ Write a Python program to get the smallest number from a list.

ANS:=
# Define a function called smallest_num_in_list that takes a list 'list' as input
def smallest_num_in_list(list):
# Initialize a variable 'min' with the first element of the input list as the initial minimum
min = list[0]
# Iterate through each element 'a' in the input list 'list'
for a in list:
# Check if the current element 'a' is smaller than the current minimum 'min'
if a < min:
# If 'a' is smaller, update the minimum 'min' to 'a'
min = a
# Return the final minimum value in the list
return min
# Call the smallest_num_in_list function with the list [1, 2, -8, 0] as input and print the result
print(smallest_num_in_list([1, 2, -8, 0]))

OUTPUT:=
-8

\\ Write a Python program to count the number of strings from a given list of strings. The
string length is 2 or more and the first and last characters are the same.

ANS:=
# Define a function called match_words that takes a list of words 'words' as input
def match_words(words):
# Initialize a counter 'ctr' to keep track of matching words
ctr = 0

# Iterate through each word in the input list 'words'


for word in words:
# Check if the word has a length greater than 1 and its first and last characters are the same
if len(word) > 1 and word[0] == word[-1]:
# If the condition is met, increment the counter 'ctr'
ctr += 1

# Return the final count of matching words


return ctr
# Call the match_words function with the list ['abc', 'xyz', 'aba', '1221'] as input and print the result
print(match_words(['abc', 'xyz', 'aba', '1221']))

OUTPUT:=
2

\\ Write a Python program to get a list, sorted in increasing order by


the last element in each tuple from a given list of non-empty tuples.

ANS:=
# Define a function called 'last' that takes a single argument 'n' and returns the last element of 'n'
def last(n):
return n[-1]
# Define a function called 'sort_list_last' that takes a list of tuples 'tuples' as input
def sort_list_last(tuples):
# Sort the list of tuples 'tuples' using the 'last' function as the key for sorting
return sorted(tuples, key=last)
# Call the 'sort_list_last' function with a list of tuples as input and print the sorted result
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

OUTPUT:=
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

\\ Write a Python program to remove duplicates from a list

ANS:=
# Define a list 'a' with some duplicate and unique elements
a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]
# Create an empty set to store duplicate items and an empty list for unique items
dup_items = set()
uniq_items = []
# Iterate through each element 'x' in the list 'a'
for x in a:
# Check if the current element 'x' is not already in the set 'dup_items' (it's a duplicate check)
if x not in dup_items:
# If 'x' is not a duplicate, add it to the 'uniq_items' list
uniq_items.append(x)
# Add 'x' to the 'dup_items' set to mark it as a seen item
dup_items.add(x)
# Print the set 'dup_items' which now contains the unique elements from the original list 'a'
print(dup_items)

OUTPUT:=
{40, 10, 80, 50, 20, 60, 30}

You might also like