Solution on Class and Object

October 9, 2025

🧩 1. Define a Basic Class

Problem:
Create a class Car with attributes brand, model, and year.
Include a method start_engine() that prints a message like:
"The 2022 Tesla Model S engine has started."

Explanation:
A simple intro to defining a class, initializing attributes, and using them in a method.

Solution:

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

    def start_engine(self):
        print(f"The {self.year} {self.brand} {self.model} engine has started.")

car1 = Car("Tesla", "Model S", 2022)
car1.start_engine()


🧩 2. Class Representing a Movie

Problem:
Create a class Movie with attributes title, director, and rating.
Add a method describe() that prints all details in one line.
Then create two movie objects and display their information.

Explanation:
Practices constructors, instance variables, and string formatting.

Solution:

class Movie:
    def __init__(self, title, director, rating):
        self.title = title
        self.director = director
        self.rating = rating

    def describe(self):
        print(f"🎬 {self.title} directed by {self.director} — Rating: {self.rating}/10")

m1 = Movie("Inception", "Christopher Nolan", 9)
m2 = Movie("Interstellar", "Christopher Nolan", 8.5)
m1.describe()
m2.describe()


🧩 3. Shopping Cart with Total Calculation

Problem:
Create a class ShoppingCart that keeps a list of items and their prices.
Add methods:

  • add_item(name, price) → adds an item to cart
  • total() → returns total price of all items

Explanation:
Introduces data storage in objects (using lists).

Solution:

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, name, price):
        self.items.append((name, price))

    def total(self):
        total_price = sum(price for _, price in self.items)
        return total_price

cart = ShoppingCart()
cart.add_item("Laptop", 800)
cart.add_item("Mouse", 20)
print("Total Bill:", cart.total())


🧩 4. Track Employee Bonuses

Problem:
Create a class Employee with name and salary.
Add a method apply_bonus(percent) that increases salary by the given percentage.
Show the old and new salary.

Explanation:
Covers arithmetic operations inside methods and modifying attributes.

Solution:

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

    def apply_bonus(self, percent):
        new_salary = self.salary + (self.salary * percent / 100)
        print(f"{self.name}'s new salary after {percent}% bonus: {new_salary}")

emp = Employee("Riya", 50000)
emp.apply_bonus(10)


🧩 5. Temperature Converter

Problem:
Create a class Temperature with a Celsius value.
Add methods:

  • to_fahrenheit() — returns Fahrenheit
  • to_kelvin() — returns Kelvin

Explanation:
Good for practicing methods that return computed results.

Solution:

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def to_fahrenheit(self):
        return (self.celsius * 9/5) + 32

    def to_kelvin(self):
        return self.celsius + 273.15

temp = Temperature(25)
print("Fahrenheit:", temp.to_fahrenheit())
print("Kelvin:", temp.to_kelvin())


🧩 6. Simple Library System

Problem:
Create a class Book with attributes title, author, and is_available (default True).
Add methods:

  • borrow() → marks the book unavailable
  • return_book() → marks it available again

Explanation:
Demonstrates modifying internal state with boolean flags.

Solution:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.is_available = True

    def borrow(self):
        if self.is_available:
            self.is_available = False
            print(f"You borrowed '{self.title}'")
        else:
            print(f"'{self.title}' is currently unavailable")

    def return_book(self):
        self.is_available = True
        print(f"'{self.title}' has been returned")

book1 = Book("1984", "George Orwell")
book1.borrow()
book1.return_book()


🧩 7. Simple Bank Account with Validation

Problem:
Create a class BankAccount with holder_name and balance (default 0).
Add methods:

  • deposit(amount)
  • withdraw(amount) with validation if balance is sufficient
  • display_balance()

Explanation:
Encourages conditional logic within class methods.

Solution:

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

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited {amount}. New balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew {amount}. Remaining balance: {self.balance}")
        else:
            print("Insufficient balance!")

acc = BankAccount("Amit", 1000)
acc.deposit(500)
acc.withdraw(1200)
acc.display_balance = lambda: print(f"Final Balance: {acc.balance}")
acc.display_balance()


🧩 8. Class for Student Marks

Problem:
Create a class Student that stores name and three subject marks.
Add a method average() that returns the average mark,
and another method grade() that returns:

  • "A" if avg ≥ 80
  • "B" if avg ≥ 60
  • "C" otherwise.

Explanation:
Combines logic, arithmetic, and conditional statements.

Solution:

class Student:
    def __init__(self, name, m1, m2, m3):
        self.name = name
        self.marks = [m1, m2, m3]

    def average(self):
        return sum(self.marks) / 3

    def grade(self):
        avg = self.average()
        if avg >= 80:
            return "A"
        elif avg >= 60:
            return "B"
        else:
            return "C"

s1 = Student("Priya", 85, 78, 92)
print(f"{s1.name}'s Grade:", s1.grade())


🧩 9. Car Mileage Tracker

Problem:
Create a class MileageTracker for cars with attributes distance and fuel_used.
Add a method calculate_mileage() that returns mileage (distance / fuel).
Handle division by zero gracefully.

Explanation:
Mixes object attributes, math, and simple error handling.

Solution:

class MileageTracker:
    def __init__(self, distance, fuel_used):
        self.distance = distance
        self.fuel_used = fuel_used

    def calculate_mileage(self):
        if self.fuel_used == 0:
            return "Fuel used cannot be zero!"
        return self.distance / self.fuel_used

car = MileageTracker(500, 25)
print("Mileage:", car.calculate_mileage(), "km/l")


🧩 10. Product Discount System

Problem:
Create a class Product with name, price, and category.
Add a method apply_discount(percent) that reduces price by that percent.
Add another method display_info() to print product details.

Explanation:
Tests object creation, math operation, and clean output formatting.

Solution:

class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category

    def apply_discount(self, percent):
        self.price -= self.price * (percent / 100)

    def display_info(self):
        print(f"Product: {self.name} | Category: {self.category} | Price: ₹{self.price:.2f}")

item = Product("Headphones", 2000, "Electronics")
item.apply_discount(10)
item.display_info()

© Copyright 2025 — Fessorpro

Terms of Service / Privacy Policy