0% found this document useful (0 votes)
10 views10 pages

DS Assigment 4

The document outlines the creation of various classes in Python, including Circle, Rectangle, BankAccount, Student, Employee, Animal, Car, Person, Shape, and different types of bank accounts. Each class includes methods for specific functionalities such as calculating areas, managing bank transactions, and customizing behaviors for subclasses. Additionally, examples of usage for these classes are provided to demonstrate their implementation.
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)
10 views10 pages

DS Assigment 4

The document outlines the creation of various classes in Python, including Circle, Rectangle, BankAccount, Student, Employee, Animal, Car, Person, Shape, and different types of bank accounts. Each class includes methods for specific functionalities such as calculating areas, managing bank transactions, and customizing behaviors for subclasses. Additionally, examples of usage for these classes are provided to demonstrate their implementation.
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
You are on page 1/ 10

1.Create a class called Circle with a method to calculate the area of the circle.

2.Create a class called Rectangle with methods to calculate the area and perimeter of the rectangle.

from mimetypes import init

x=94
######
print("welcome to area calculator\n press 1 for circle\n press 2 for rectangle
\npress 3 for sqare\n press 4 for triangle \n press 5 for cube \n press 6 for
parallelogram \n press 7 for cylinder ")
choice=int(input('enter a no >>>> '))

if choice==1: #circle

r=int(input("enter your radius>> "))


areaofcircle=22/7*r*r
print('the area of your circle is >>',areaofcircle)

if choice==2: #rectangle

l=int(input("enter length>> "))


w=int(input("enter width>> "))
areaofrectangle=l*w
print('the area of your rectangle is >>',areaofrectangle)

if choice==3: #sqare

a=int(input("enter side >> "))


areaofsqare=a*a
print('the area of your sqare is >>',areaofsqare)

if choice==4: #triangle

b=int(input("enter base>> "))


h=int(input("enter higth>> "))
areaoftriangle=(b*h)/2
print('the area of your triangle is >>',areaoftriangle)

if choice==5: #cube

a=int(input("enter base>> "))


areaofcube=6*(a*a)
print('the area of your cube is >>', areaofcube)

if choice==6: #parallelogram

b=int(input("enter base>> "))


h=int(input("enter heigth>> "))
areaofparallelogram=b*h
print('the area of your parallelogram is >>',areaofparallelogram)

if choice==7: #cylinder

r=int(input("enter radius>> "))


h=int(input("enter heigth>> "))
areaofcylinder=(2*3.14*r*h)+(2*3.14*r*r)
print('the area of your cylinder is >>', areaofcylinder)

3.Create a class called BankAccount with methods to deposit, withdraw and check the balance.

class Bank_Account:
def __init__(self):
self.balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")

def deposit(self):
amount=float(input("Enter amount to be Deposited: "))
self.balance += amount
print("\n Amount Deposited:",amount)

def withdraw(self):
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
else:
print("\n Insufficient balance ")

def display(self):
print("\n Net Available Balance=",self.balance)

# Driver code

# creating an object of class


s = Bank_Account()
# Calling functions with that class object
s.deposit()
s.withdraw()
s.display()

4.Create a class called Student with methods to calculate the average grade and display the student
information.

print("Enter Marks Obtained in 5 Subjects: ")


total1 = 44
total2 = 67
total3 = 76
total4 = 99
total5 = 58

tot = total1 + total2 + total3 + total4 + total4


avg = tot / 5

if avg >= 91 and avg <= 100:


print("Your Grade is A1")
elif avg >= 81 and avg < 91:
print("Your Grade is A2")
elif avg >= 71 and avg < 81:
print("Your Grade is B1")
elif avg >= 61 and avg < 71:
print("Your Grade is B2")
elif avg >= 51 and avg < 61:
print("Your Grade is C1")
elif avg >= 41 and avg < 51:
print("Your Grade is C2")
elif avg >= 33 and avg < 41:
print("Your Grade is D")
elif avg >= 21 and avg < 33:
print("Your Grade is E1")
elif avg >= 0 and avg < 21:
print("Your Grade is E2")
else:
print("Invalid Input!")

5.Create a class called Employee with methods to calculate the salary and display the employee
information.

6. Create a class called Animal with methods to make a sound and move. Then create subclasses for
different types of animals (e.g. Dog, Cat, Bird) and override the methods to customize their behavior.
class Animal:
def __init__(self, name):
self.name = name

def make_sound(self):
pass

def move(self):
pass

class Dog(Animal):
def make_sound(self):
return f"{self.name} barks"

def move(self):
return f"{self.name} runs on four legs"

class Cat(Animal):
def make_sound(self):
return f"{self.name} meows"

def move(self):
return f"{self.name} walks on four legs"

class Bird(Animal):
def make_sound(self):
return f"{self.name} chirps"

def move(self):
return f"{self.name} flies"

# Usage
if __name__ == "__main__":
dog = Dog("Buddy")
cat = Cat("Whiskers")
bird = Bird("Polly")

print(dog.make_sound()) # Output: Buddy barks


print(cat.make_sound()) # Output: Whiskers meows
print(bird.make_sound()) # Output: Polly chirps

print(dog.move()) # Output: Buddy runs on four legs


print(cat.move()) # Output: Whiskers walks on four legs
print(bird.move()) # Output: Polly flies

7.Create a class called Car with methods to start the engine, accelerate, and brake. Then create
subclasses for different types of cars (e.g. SportsCar, SUV, Sedan) and override the methods to
customize their performance.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.speed = 0
self.engine_started = False

def start_engine(self):
self.engine_started = True
print(f"The {self.make} {self.model}'s engine is now running.")

def accelerate(self, speed_increase):


if self.engine_started:
self.speed += speed_increase
print(f"The {self.make} {self.model} is accelerating. Current
speed: {self.speed} mph.")
else:
print(f"Start the engine first to accelerate the {self.make}
{self.model}.")

def brake(self, speed_decrease):


if self.speed > 0:
self.speed -= speed_decrease
print(f"The {self.make} {self.model} is braking. Current speed:
{self.speed} mph.")
else:
print(f"The {self.make} {self.model} is already stationary.")

class SportsCar(Car):
def __init__(self, make, model):
super().__init__(make, model)
self.sport_mode = False

def enable_sport_mode(self):
self.sport_mode = True
print(f"Sport mode enabled for the {self.make} {self.model}. It's
ready for high performance!")

def accelerate(self, speed_increase):


if self.sport_mode:
super().accelerate(speed_increase * 1.5) # Sports cars accelerate
faster
else:
super().accelerate(speed_increase)

class SUV(Car):
def __init__(self, make, model):
super().__init__(make, model)
self.off_road_mode = False

def enable_off_road_mode(self):
self.off_road_mode = True
print(f"Off-road mode enabled for the {self.make} {self.model}. It can
handle rough terrain with ease!")

def brake(self, speed_decrease):


if self.off_road_mode:
super().brake(speed_decrease / 2) # SUVs have enhanced braking
for off-road control
else:
super().brake(speed_decrease)

class Sedan(Car):
def __init__(self, make, model):
super().__init__(make, model)

# usage:
if __name__ == "__main__":
sports_car = SportsCar("Ferrari", "488 GTB")
suv = SUV("Jeep", "Grand Cherokee")
sedan = Sedan("Toyota", "Camry")

sports_car.start_engine()
suv.start_engine()
sedan.start_engine()

sports_car.enable_sport_mode()
suv.enable_off_road_mode()

sports_car.accelerate(50)
suv.accelerate(40)
sedan.accelerate(30)

sports_car.brake(20)
suv.brake(15)
sedan.brake(10)

8.Create a class called Person with methods to speak and walk. Then create subclasses for different
types of people (e.g. Teacher, Student, Athlete) and override the methods to reflect their roles and
personalities.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f"{self.name} is speaking.")

def walk(self):
print(f"{self.name} is walking.")

class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject

def speak(self):
print(f"{self.name} is teaching {self.subject}.")

class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade

def speak(self):
print(f"{self.name} is studying in grade {self.grade}.")

class Athlete(Person):
def __init__(self, name, age, sport):
super().__init__(name, age)
self.sport = sport

def walk(self):
print(f"{self.name} is walking to practice for {self.sport}.")

def speak(self):
print(f"{self.name} is an athlete who plays {self.sport}.")

# Example usage:
teacher = Teacher("Mr. Smith", 35, "Math")
student = Student("Alice", 16, 10)
athlete = Athlete("John", 25, "Basketball")

teacher.speak() # Output: Mr. Smith is teaching Math.


student.speak() # Output: Alice is studying in grade 10.
athlete.speak() # Output: John is an athlete who plays Basketball.

teacher.walk() # Output: Mr. Smith is walking.


athlete.walk()
9.Create a class called Shape with methods to calculate the area and perimeter. Then create
subclasses for different types of shapes (e.g. Rectangle, Triangle, Circle) and override the methods to
specialize the calculations.

import math

class Shape:
def area(self):
pass

def perimeter(self):
pass

class Rectangle(Shape):
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)

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

def area(self):
return 0.5 * self.base * self.height

def perimeter(self):
return self.side1 + self.side2 + self.side3

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

def area(self):
return math.pi * self.radius**2

def perimeter(self):
return 2 * math.pi * self.radius
# Example usage:
rectangle = Rectangle(5, 3)
print("Rectangle Area:", rectangle.area())
print("Rectangle Perimeter:", rectangle.perimeter())

triangle = Triangle(4, 3, 5, 6, 7)
print("Triangle Area:", triangle.area())
print("Triangle Perimeter:", triangle.perimeter())

circle = Circle(4)
print("Circle Area:", circle.area())
print("Circle Circumference:", circle.perimeter())

10.Create a class called BankAccount with methods to deposit and withdraw money. Then create
subclasses for different types of accounts (e.g. Checking Account, Savings Account,
MoneyMarketAccount) and override the methods to reflect their features and restrictions.

class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance

def deposit(self, amount):


if amount > 0:
self.balance += amount
return f"Deposited ${amount}. New balance: ${self.balance}"
else:
return "Invalid deposit amount."

def withdraw(self, amount):


if amount > 0 and amount <= self.balance:
self.balance -= amount
return f"Withdrew ${amount}. New balance: ${self.balance}"
else:
return "Invalid withdrawal amount or insufficient balance."

class CheckingAccount(BankAccount):
def __init__(self, account_number, balance=0, overdraft_limit=100):
super().__init__(account_number, balance)
self.overdraft_limit = overdraft_limit

def withdraw(self, amount):


if amount > 0 and amount <= self.balance + self.overdraft_limit:
self.balance -= amount
return f"Withdrew ${amount}. New balance: ${self.balance}"
else:
return "Invalid withdrawal amount or overdraft limit reached."

class SavingsAccount(BankAccount):
def __init__(self, account_number, balance=0, interest_rate=0.02):
super().__init__(account_number, balance)
self.interest_rate = interest_rate

def add_interest(self):
interest = self.balance * self.interest_rate
self.balance += interest
return f"Added ${interest} in interest. New balance: ${self.balance}"

class MoneyMarketAccount(BankAccount):
def __init__(self, account_number, balance=0, monthly_withdraw_limit=6):
super().__init__(account_number, balance)
self.monthly_withdraw_limit = monthly_withdraw_limit
self.monthly_withdraw_count = 0

def withdraw(self, amount):


if amount > 0 and amount <= self.balance and
self.monthly_withdraw_count < self.monthly_withdraw_limit:
self.balance -= amount
self.monthly_withdraw_count += 1
return f"Withdrew ${amount}. New balance: ${self.balance}"
elif self.monthly_withdraw_count >= self.monthly_withdraw_limit:
return "Monthly withdrawal limit exceeded."
else:
return "Invalid withdrawal amount or insufficient balance."

# usage:
checking_account = CheckingAccount("C12345", 1000, overdraft_limit=200)
print(checking_account.deposit(500))
print(checking_account.withdraw(1500))

savings_account = SavingsAccount("S67890", 2000, interest_rate=0.03)


print(savings_account.deposit(1000))
print(savings_account.add_interest())

money_market_account = MoneyMarketAccount("M54321", 3000)


print(money_market_account.deposit(800))
print(money_market_account.withdraw(500))
print(money_market_account.withdraw(400))
print(money_market_account.withdraw(300))

You might also like