Problem Based Learning
E-Commerce Cart
System Use Case:
An online shopping site needs a simple shopping cart feature.
Modules:
product.py: Manage products (name, price, stock).
cart.py: Add/remove products, view cart total.
discounts.py: Apply coupon codes and discounts.
payment.py: Simulate payment processing.
Ans:
product.py
class Product:
def init (self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def str (self):
return f"{self.name} - ₹{self.price} (Stock: {self.stock})"
cart.py
from product import Product
class Cart:
def init (self):
self.items = {}
def add_product(self, product, quantity):
if product.stock >= quantity:
self.items[product] = self.items.get(product, 0) + quantity
product.stock -= quantity
print(f"Added {quantity} x {product.name} to cart.")
else:
print("Not enough stock available.")
def remove_product(self, product, quantity):
if product in self.items and self.items[product] >= quantity:
self.items[product] -= quantity
product.stock += quantity
if self.items[product] == 0:
del self.items[product]
print(f"Removed {quantity} x {product.name} from cart.")
else:
print("Item not in cart or invalid quantity.")
def total_price(self):
return sum(product.price * quantity for product, quantity in self.items.items())
def view_cart(self):
for product, quantity in self.items.items():
print(f"{product.name} x {quantity} - ₹{product.price * quantity}")
print(f"Total: ₹{self.total_price()}")
discounts.py
class Discount:
coupons = {"SAVE10": 0.10, "OFF20": 0.20}
@staticmethod
def apply_discount(total, coupon_code):
if coupon_code in Discount.coupons:
discount = total * Discount.coupons[coupon_code]
return total - discount
return total
payment.py
class Payment:
@staticmethod
def process_payment(amount):
print(f"Processing payment of ₹
{amount}...") print("Payment successful!")
main.py
from product import Product
from cart import Cart
from discounts import Discount
from payment import Payment
p1 = Product("Laptop", 50000, 5)
p2 = Product("Phone", 25000, 10)
cart = Cart()
cart.add_product(p1, 1)
cart.add_product(p2, 2)
cart.view_cart()
total = cart.total_price()
total_after_discount = Discount.apply_discount(total, "SAVE10")
print(f"Total after discount: ₹{total_after_discount}")
Payment.process_payment(total_after_discount)
Library Management System
Use Case:
A school/college library wants to automate book issue/return management.
Modules:
book.py: Functions to add, remove, search for books.
member.py: Functions to add members, check borrowing limits.
transaction.py: Issue, return, calculate overdue fines.
reports.py: Generate reports (issued books, fines due).
Ans:
book.py
class Book:
def init (self, title, author, book_id, copies):
self.title = title
self.author = author
self.book_id = book_id
self.copies = copies
def str (self):
return f"{self.book_id}: {self.title} by {self.author} (Copies: {self.copies})"
class Library:
def init (self):
self.books = {}
def add_book(self, book):
self.books[book.book_id] = book
print(f"Book '{book.title}' added.")
def remove_book(self, book_id):
if book_id in self.books:
del self.books[book_id]
print("Book removed.")
else:
print("Book not found.")
def search_book(self, title):
for book in self.books.values():
if book.title.lower() == title.lower():
return book
return "Book not found."
member.py
class Member:
def init (self, member_id, name, max_books=3):
self.member_id = member_id
self.name = name
self.borrowed_books = []
self.max_books = max_books
def can_borrow(self):
return len(self.borrowed_books) < self.max_books
def str (self):
return f"Member {self.member_id}: {self.name} (Borrowed:
{len(self.borrowed_books)}/{self.max_books})"
transaction.py
from datetime import datetime, timedelta
class Transaction:
def init (self):
self.issued_books = {} # {book_id: (member_id, issue_date)}
def issue_book(self, book, member):
if book.copies > 0 and member.can_borrow():
issue_date = datetime.now()
self.issued_books[book.book_id] = (member.member_id, issue_date)
book.copies -= 1
member.borrowed_books.append(book)
print(f"Book '{book.title}' issued to {member.name}.")
else:
print("Cannot issue book. Either out of stock or limit reached.")
def return_book(self, book, member):
if book.book_id in self.issued_books:
issue_date = self.issued_books.pop(book.book_id)[1]
return_date = datetime.now()
overdue_days = (return_date - issue_date).days - 14 # 14-day limit
fine = max(0, overdue_days * 10) # ₹10 per overdue day
book.copies += 1
member.borrowed_books.remove(book)
print(f"Book '{book.title}' returned by {member.name}. Fine: ₹{fine}")
else:
print("Book not found in issued records.")
reports.py
class Reports:
@staticmethod
def issued_books(transaction, library):
print("\nIssued Books Report:")
for book_id, (member_id, issue_date) in transaction.issued_books.items():
book = library.books.get(book_id)
print(f"{book.title} issued to Member {member_id} on {issue_date}")
@staticmethod
def calculate_fines(transaction):
print("\nFines Due Report:")
from datetime import datetime
for book_id, (member_id, issue_date) in transaction.issued_books.items():
overdue_days = (datetime.now() - issue_date).days - 14
if overdue_days > 0:
fine = overdue_days * 10
print(f"Member {member_id} has ₹{fine} fine for Book ID {book_id}.")
main.py
from book import Book, Library
from member import Member
from transaction import Transaction
from reports import Reports
library = Library()
transaction = Transaction()
book1 = Book("Python Basics", "John Doe", 101, 5)
book2 = Book("Data Science", "Jane Smith", 102, 3)
library.add_book(book1)
library.add_book(book2)
member1 = Member(1, "Alice")
member2 = Member(2, "Bob")
transaction.issue_book(book1, member1)
transaction.issue_book(book2, member2)
Reports.issued_books(transaction, library)
transaction.return_book(book1, member1)
Reports.calculate_fines(transaction)
Hotel Reservation System
Use Case:
A hotel booking application where users book rooms, check availability, and manage
payments.
Modules:
rooms.py: Manage room types, availability.
booking.py: Reserve/cancel bookings.
billing.py: Calculate charges, generate bills.
customer.py: Customer registration and login.
Ans:
rooms.py
class Room:
def init (self, room_number, room_type, price, available=True):
self.room_number = room_number
self.room_type = room_type
self.price = price
self.available = available
def str (self):
status = "Available" if self.available else "Booked"
return f"Room {self.room_number}: {self.room_type} - ₹{self.price} ({status})"
class Hotel:
def init (self):
self.rooms = {}
def add_room(self, room):
self.rooms[room.room_number] =
room
def check_availability(self):
return [room for room in self.rooms.values() if room.available]
booking.py
from rooms import Room, Hotel
class Booking:
def init (self):
self.bookings = {} # {room_number: customer_id}
def reserve_room(self, customer_id, hotel, room_number):
if room_number in hotel.rooms and hotel.rooms[room_number].available:
hotel.rooms[room_number].available = False
self.bookings[room_number] = customer_id
print(f"Room {room_number} booked for Customer {customer_id}.")
else:
print("Room not available.")
def cancel_booking(self, hotel, room_number):
if room_number in self.bookings:
del self.bookings[room_number]
hotel.rooms[room_number].available = True
print(f"Booking for Room {room_number} canceled.")
else:
print("No booking found for this room.")
billing.py
class Billing:
def init (self):
self.bills = {} # {customer_id: total_amount}
def generate_bill(self, customer_id, hotel, room_number, nights):
if room_number in hotel.rooms:
total_cost = hotel.rooms[room_number].price * nights
self.bills[customer_id] = total_cost
print(f"Bill for Customer {customer_id}: ₹{total_cost} for {nights} nights.")
else:
print("Invalid room number.")
customer.py
class Customer:
def init (self, customer_id, name, contact):
self.customer_id = customer_id
self.name = name
self.contact = contact
def str (self):
return f"Customer {self.customer_id}: {self.name}, Contact: {self.contact}"
main.py
from rooms import Room, Hotel
from booking import Booking
from billing import Billing
from customer import Customer
hotel = Hotel()
booking =
Booking() billing =
Billing()
hotel.add_room(Room(101, "Deluxe", 5000))
hotel.add_room(Room(102, "Suite", 8000))
customer1 = Customer(1, "Alice", "9876543210")
available_rooms = hotel.check_availability() print("\
nAvailable Rooms:")
for room in available_rooms:
print(room)
booking.reserve_room(customer1.customer_id, hotel, 101)
billing.generate_bill(customer1.customer_id, hotel, 101, 3)
booking.cancel_booking(hotel, 101)
available_rooms = hotel.check_availability()
print("\nAvailable Rooms After Cancellation:")
for room in available_rooms:
print(room)
Student Grading System
Use Case:
A teacher needs an app to calculate grades, store student info, and generate reports.
Modules:
student.py: Student details (name, roll number).
marks.py: Add marks, calculate total and average.
grading.py: Assign grades based on total marks.
report.py: Generate report cards.
Ans:
student.py
class Student:
def init (self, roll_no, name):
self.roll_no = roll_no
self.name = name
def str (self):
return f"Roll No: {self.roll_no}, Name: {self.name}"
marks.py
class Marks:
def init (self):
self.student_marks = {} # {roll_no: [marks]}
def add_marks(self, roll_no, marks):
self.student_marks[roll_no] = marks
print(f"Marks added for Roll No {roll_no}")
def calculate_total(self, roll_no):
return sum(self.student_marks.get(roll_no, []))
def calculate_average(self, roll_no):
marks = self.student_marks.get(roll_no, [])
return sum(marks) / len(marks) if marks else 0
grading.py
class Grading:
@staticmethod
def assign_grade(total):
if total >= 90:
return "A+"
elif total >= 80:
return "A"
elif total >= 70:
return "B"
elif total >=
60:
return "C"
elif total >=
50:
return "D"
else:
return "F (Fail)"
report.py
from grading import Grading
class Report:
@staticmethod
def generate_report(student, marks_module):
total = marks_module.calculate_total(student.roll_no)
average = marks_module.calculate_average(student.roll_no)
grade = Grading.assign_grade(average)
print("\nStudent Report:")
print(f"{student}")
print(f"Total Marks: {total}")
print(f"Average Marks: {average:.2f}")
print(f"Grade: {grade}")
main.py
from student import Student
from marks import Marks
from grading import Grading
from report import Report
marks_module = Marks()
student1 = Student(101, "Alice")
student2 = Student(102, "Bob")
marks_module.add_marks(student1.roll_no, [85, 90, 78, 92, 88]) # 5 subjects
marks_module.add_marks(student2.roll_no, [60, 70, 55, 65, 75])
Report.generate_report(student1, marks_module)
Report.generate_report(student2, marks_module)