0% found this document useful (0 votes)
6 views24 pages

Transaction and Student Management System

The document contains multiple Python scripts for various applications including a transaction manager, a student management system, a library system, a secure note application, a quiz application, and a bank account management system. Each script implements specific functionalities such as adding, viewing, updating, and deleting records, as well as encrypting notes and conducting quizzes. The overall structure emphasizes file handling, data serialization with pickle, and basic user interactions.

Uploaded by

chitishaagarwal9
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)
6 views24 pages

Transaction and Student Management System

The document contains multiple Python scripts for various applications including a transaction manager, a student management system, a library system, a secure note application, a quiz application, and a bank account management system. Each script implements specific functionalities such as adding, viewing, updating, and deleting records, as well as encrypting notes and conducting quizzes. The overall structure emphasizes file handling, data serialization with pickle, and basic user interactions.

Uploaded by

chitishaagarwal9
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

Assignment-3

1)FILENAME = "[Link]"

try:

open(FILENAME, "r").close()

except FileNotFoundError:

with open(FILENAME, "w") as f:

[Link]("type,amount,category\n")

def add_income(amount, category):

with open(FILENAME, "a") as f:

[Link]("income," + str(amount) + "," + category + "\n")

def add_expense(amount, category):

with open(FILENAME, "a") as f:

[Link]("expense," + str(amount) + "," + category + "\n")

def get_balance():

income, expense = 0, 0

with open(FILENAME, "r") as f:

[Link]()

for line in f:

parts = [Link]().split(",")

if len(parts) == 3:

t_type, amount, category = parts

amount = float(amount)

if t_type == "income":

income += amount

elif t_type == "expense":

expense += amount

return income - expense

def show_summary():

print("\n--- Transactions Summary ---")

with open(FILENAME, "r") as f:

for line in f:

print([Link]())

def export_data(out_file):

with open(FILENAME, "r") as f_in:

data = f_in.read()

with open(out_file, "w") as f_out:

f_out.write(data)

if __name__ == "__main__":

add_income(2000, "Salary")

add_expense(500, "Food")

add_expense(200, "Transport")
print("Total Balance:", get_balance())

show_summary()

export_data("[Link]")

OUTPUT:-

2) import pickle

class Student:

def __init__(self, roll, name, marks):

[Link] = roll

[Link] = name

[Link] = marks # list of 3 marks

[Link] = sum(marks)

[Link] = self.calculate_grade()

def calculate_grade(self):

avg = [Link] / 3

if avg >= 90:

return 'A'

elif avg >= 75:

return 'B'

elif avg >= 50:

return 'C'

else:

return 'F'

def display(self):

print(f"Roll: {[Link]}, Name: {[Link]}, Marks: {[Link]}, "

f"Total: {[Link]}, Grade: {[Link]}")

FILENAME = "[Link]"

def save_record(student):

with open(FILENAME, "ab") as f:

[Link](student, f)

def view_records():

try:

with open(FILENAME, "rb") as f:

while True:

student = [Link](f)

[Link]()

except (EOFError, FileNotFoundError):

pass
def update_record(roll):

students = []

updated = False

try:

with open(FILENAME, "rb") as f:

while True:

student = [Link](f)

if [Link] == roll:

name = input("Enter new name: ")

marks = [int(input(f"Enter mark {i+1}: ")) for i in range(3)]

student = Student(roll, name, marks)

updated = True

[Link](student)

except (EOFError, FileNotFoundError):

pass

with open(FILENAME, "wb") as f:

for s in students:

[Link](s, f)

if updated:

print("Record updated successfully!")

else:

print("Roll number not found!")

def delete_record(roll):

students = []

deleted = False

try:

with open(FILENAME, "rb") as f:

while True:

student = [Link](f)

if [Link] != roll:

[Link](student)

else:

deleted = True

except (EOFError, FileNotFoundError):

pass

with open(FILENAME, "wb") as f:

for s in students:

[Link](s, f)

if deleted:

print("Record deleted successfully!")

else:

print("Roll number not found!")

if __name__ == "__main__":

while True:

print("\n--- Student Management System ---")


print("1. Add Student")

print("2. View Students")

print("3. Update Student")

print("4. Delete Student")

print("5. Exit")

choice = input("Enter choice: ")

if choice == "1":

roll = int(input("Enter roll number: "))

name = input("Enter name: ")

marks = [int(input(f"Enter mark {i+1}: ")) for i in range(3)]

student = Student(roll, name, marks)

save_record(student)

print("Record added successfully!")

elif choice == "2":

view_records()

elif choice == "3":

roll = int(input("Enter roll number to update: "))

update_record(roll)

elif choice == "4":

roll = int(input("Enter roll number to delete: "))

delete_record(roll)

elif choice == "5":

break

else:

print("Invalid choice!")

OUTPUT:-

3) #[Link]
import pickle

BOOK_FILE = "[Link]"

class Book:

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

self.book_id = book_id

[Link] = title

[Link] = author

[Link] = True
def display(self):

status = "Available" if [Link] else "Issued"

print(f"ID: {self.book_id}, Title: {[Link]}, Author: {[Link]}, Status: {status}")

def save_books(books):

with open(BOOK_FILE, "wb") as f:

[Link](books, f)

def load_books():

try:

with open(BOOK_FILE, "rb") as f:

return [Link](f)

except (FileNotFoundError, EOFError):

return []

#[Link]

from [Link] import load_books, save_books

class User:

def __init__(self, user_id, name):

self.user_id = user_id

[Link] = name

self.borrowed_books = []

def search_book(self, keyword):

books = load_books()

found = [b for b in books if [Link]() in [Link]() or [Link]() in [Link]()]

if found:

for book in found:

[Link]()

else:

print("No book found!")

def borrow_book(self, book_id):

books = load_books()

for b in books:

if b.book_id == book_id:

if [Link]:

[Link] = False

self.borrowed_books.append(b.book_id)

save_books(books)

print(f"{[Link]} borrowed {[Link]}")

else:

print("Book already issued!")

return

print("Book not found!")

def return_book(self, book_id):

books = load_books()

for b in books:
if b.book_id == book_id:

if book_id in self.borrowed_books:

[Link] = True

self.borrowed_books.remove(book_id)

save_books(books)

print(f"{[Link]} returned {[Link]}")

else:

print(f"{[Link]} did not borrow this book")

return

print("Book not found!")

#[Link]

from [Link] import Book, load_books, save_books

class Admin:

def __init__(self, name="Admin"):

[Link] = name

def add_book(self, book_id, title, author):

books = load_books()

for b in books:

if b.book_id == book_id:

print("Book ID already exists!")

return

new_book = Book(book_id, title, author)

[Link](new_book)

save_books(books)

print("Book added successfully!")

def view_books(self):

books = load_books()

if books:

for b in books:

[Link]()

else:

print("No books in inventory.")

def remove_book(self, book_id):

books = load_books()

new_books = [b for b in books if b.book_id != book_id]

if len(new_books) != len(books):

save_books(new_books)

print("Book removed successfully!")

else:

print("Book ID not found!")

#[Link]

from [Link] import Admin


from [Link] import User

if __name__ == "__main__":

admin = Admin()

user = User(1, "Krrish")

while True:

print("\n--- Library System ---")

print("1. Admin - Add Book")

print("2. Admin - View Books")

print("3. Admin - Remove Book")

print("4. User - Search Book")

print("5. User - Borrow Book")

print("6. User - Return Book")

print("7. Exit")

choice = input("Enter choice: ")

if choice == "1":

bid = input("Enter Book ID: ")

title = input("Enter Title: ")

author = input("Enter Author: ")

admin.add_book(bid, title, author)

elif choice == "2":

admin.view_books()

elif choice == "3":

bid = input("Enter Book ID to remove: ")

admin.remove_book(bid)

elif choice == "4":

keyword = input("Enter keyword to search: ")

user.search_book(keyword)

elif choice == "5":

bid = input("Enter Book ID to borrow: ")

user.borrow_book(bid)

elif choice == "6":

bid = input("Enter Book ID to return: ")

user.return_book(bid)

elif choice == "7":

break

else:

print("Invalid choice!")
OUTPUT:-

4) #[Link]
import base64

def caesar_encrypt(text, shift=3):

result = ""

for char in text:

if [Link]():

base = 'A' if [Link]() else 'a'

result += chr((ord(char) - ord(base) + shift) % 26 + ord(base))

else:

result += char

return result

def caesar_decrypt(text, shift=3):

return caesar_encrypt(text, -shift)

def base64_encrypt(text):

return base64.b64encode([Link]()).decode()

def base64_decrypt(text):

return base64.b64decode([Link]()).decode()

#[Link]

from [Link] import caesar_encrypt, caesar_decrypt, base64_encrypt, base64_decrypt

class SecureNote:

def __init__(self, filename="[Link]"):

[Link] = filename
def write_note(self, note, method="caesar"):

"""Encrypts and saves a note to file."""

if method == "caesar":

encrypted = caesar_encrypt(note)

tag = "caesar"

elif method == "base64":

encrypted = base64_encrypt(note)

tag = "base64"

else:

raise ValueError("Invalid encryption method")

with open([Link], "a") as f:

[Link](f"{tag}:{encrypted}\n")

print("Note saved securely!")

def read_notes(self):

try:

with open([Link], "r") as f:

lines = [Link]()

except FileNotFoundError:

print("No notes found!")

return

for line in lines:

method, encrypted = [Link]().split(":", 1)

if method == "caesar":

decrypted = caesar_decrypt(encrypted)

elif method == "base64":

decrypted = base64_decrypt(encrypted)

else:

decrypted = "[Unknown method]"

print(f"[{method}] {decrypted}")

#[Link]

from [Link] import SecureNote

if __name__ == "__main__":

sn = SecureNote()

while True:

print("\n--- Secure Note App ---")

print("1. Write a Note")

print("2. Read Notes")

print("3. Exit")

choice = input("Enter choice: ")

if choice == "1":

note = input("Enter your note: ")

method = input("Choose method (caesar/base64): ").lower()


sn.write_note(note, method)

elif choice == "2":

sn.read_notes()

elif choice == "3":

break

else:

print("Invalid choice!")

OUTPUT:-

5)import datetime

class Quiz:

def __init__(self, questions_file, log_file="[Link]"):

self.questions_file = questions_file

self.log_file = log_file

[Link] = []

[Link] = 0

def load_questions(self):

try:

with open(self.questions_file, "r") as f:

for line in f:

parts = [Link]().split("|")

if len(parts) == 6:

question, *options, correct = parts

[Link]({

"question": question,

"options": options,

"answer": int(correct)

})

except FileNotFoundError:

print("Questions file not found!")

exit(1)

def conduct_quiz(self):

print("\n===== QUIZ START =====\n")

for i, q in enumerate([Link], 1):

print(f"Q{i}. {q['question']}")

for idx, opt in enumerate(q["options"], 1):

print(f" {idx}. {opt}")


while True:

try:

choice = int(input("Your answer (1-4): "))

if 1 <= choice <= 4:

break

else:

print("Invalid choice. Enter 1-4.")

except ValueError:

print("Please enter a number (1-4).")

if choice == q["answer"]:

print("✅ Correct!\n")

[Link] += 1

else:

print(f"❌ Wrong! Correct answer: {q['options'][q['answer']-1]}\n")

def evaluate_results(self):

total = len([Link])

percentage = ([Link] / total) * 100 if total > 0 else 0

print("===== QUIZ RESULTS =====")

print(f"Score: {[Link]}/{total}")

print(f"Percentage: {percentage:.2f}%")

return total, percentage

def save_results(self, username="User"):

total, percentage = self.evaluate_results()

with open(self.log_file, "a") as f:

[Link](f"{[Link]()} | {username} | "

f"Score: {[Link]}/{total} | {percentage:.2f}%\n")

print(f"\nResults saved to {self.log_file}")

if __name__ == "__main__":

quiz = Quiz("[Link]")

quiz.load_questions()

name = input("Enter your name: ")

quiz.conduct_quiz()

quiz.save_results(name)
OUTPUT:-

6) import datetime
import os

class BankAccount:

def __init__(self, account_number, holder_name, balance=0):

self.account_number = account_number

self.holder_name = holder_name

[Link] = balance

self.log_file = f"{self.account_number}_transactions.log"

if not [Link](self.log_file):
with open(self.log_file, "w") as f:

[Link]("=== Transaction History ===\n")

def log_transaction(self, action, amount, status="SUCCESS"):

with open(self.log_file, "a") as f:

[Link](f"{[Link]()} | {action} | Amount: {amount} | "

f"Balance: {[Link]} | {status}\n")

def deposit(self, amount):

if amount <= 0:

print("❌ Deposit amount must be positive!")

self.log_transaction("DEPOSIT", amount, "FAILED")

return

[Link] += amount

print(f"✅ Deposited {amount}. New Balance = {[Link]}")

self.log_transaction("DEPOSIT", amount)

def withdraw(self, amount):

if amount <= 0:

print("❌ Withdrawal amount must be positive!")

self.log_transaction("WITHDRAW", amount, "FAILED")

return

if amount > [Link]:

print("❌ Insufficient funds!")

self.log_transaction("WITHDRAW", amount, "FAILED")

return

[Link] -= amount

print(f"✅ Withdrawn {amount}. New Balance = {[Link]}")

self.log_transaction("WITHDRAW", amount)

def transfer(self, to_account, amount):

if amount <= 0:

print("❌ Transfer amount must be positive!")

self.log_transaction("TRANSFER", amount, "FAILED")

return

if amount > [Link]:

print("❌ Insufficient funds for transfer!")

self.log_transaction("TRANSFER", amount, "FAILED")

return

[Link] -= amount

to_account.balance += amount

print(f"✅ Transferred {amount} to {to_account.holder_name} "

f"({to_account.account_number}). New Balance = {[Link]}")

self.log_transaction(f"TRANSFER to {to_account.account_number}", amount)

to_account.log_transaction(f"TRANSFER from {self.account_number}", amount)


def show_balance(self):

print(f"Account {self.account_number} | Holder: {self.holder_name} | Balance: {[Link]}")

class SavingsAccount(BankAccount):

def __init__(self, account_number, holder_name, balance=0, interest_rate=0.03):

super().__init__(account_number, holder_name, balance)

self.interest_rate = interest_rate

def add_interest(self):

interest = [Link] * self.interest_rate

[Link] += interest

print(f"✅ Interest {interest:.2f} added. New Balance = {[Link]}")

self.log_transaction("INTEREST", interest)

class CurrentAccount(BankAccount):

def __init__(self, account_number, holder_name, balance=0, overdraft_limit=5000):

super().__init__(account_number, holder_name, balance)

self.overdraft_limit = overdraft_limit

def withdraw(self, amount):

if amount <= 0:

print("❌ Withdrawal amount must be positive!")

self.log_transaction("WITHDRAW", amount, "FAILED")

return

if amount > [Link] + self.overdraft_limit:

print("❌ Exceeds overdraft limit!")

self.log_transaction("WITHDRAW", amount, "FAILED")

return

[Link] -= amount

print(f"✅ Withdrawn {amount}. New Balance = {[Link]}")

self.log_transaction("WITHDRAW", amount)

if __name__ == "__main__":

# Create accounts

acc1 = SavingsAccount("SAV123", "Alice", 1000)

acc2 = CurrentAccount("CUR456", "Bob", 500)

# Perform operations

[Link](500)

[Link](200)

acc1.add_interest()

[Link](1000) # overdraft allowed

[Link](acc2, 300)

print("\n--- Final Balances ---")

acc1.show_balance()

acc2.show_balance()
OUTPUT:-

7)import datetime
import os

class Employee:

def __init__(self, emp_id, name, designation, basic_salary):

self.emp_id = emp_id

[Link] = name

[Link] = designation

self.basic_salary = basic_salary

class Payslip:

def __init__(self, employee, work_days, deductions):

[Link] = employee

self.work_days = work_days

[Link] = deductions

self.net_salary = 0

self.gross_salary = 0

def calculate_salary(self):

# Assuming salary is for 30 working days

per_day_salary = [Link].basic_salary / 30

self.gross_salary = per_day_salary * self.work_days

self.net_salary = self.gross_salary - [Link]

if self.net_salary < 0:

self.net_salary = 0

def generate_payslip(self):

self.calculate_salary()

filename = f"payslip_{[Link].emp_id}.txt"

with open(filename, "w") as f:

[Link]("========================================\n")

[Link](" EMPLOYEE PAYSLIP\n")

[Link]("========================================\n")

[Link](f"Date: {[Link]().strftime('%d-%m-%Y')}\n\n")

[Link](f"Employee ID : {[Link].emp_id}\n")

[Link](f"Name : {[Link]}\n")

[Link](f"Designation : {[Link]}\n")

[Link]("----------------------------------------\n")

[Link](f"Basic Salary : {[Link].basic_salary:.2f}\n")

[Link](f"Work Days : {self.work_days}/30\n")

[Link](f"Gross Salary : {self.gross_salary:.2f}\n")

[Link](f"Deductions : {[Link]:.2f}\n")

[Link]("----------------------------------------\n")
[Link](f"Net Salary : {self.net_salary:.2f}\n")

[Link]("========================================\n")

print(f"✅ Payslip generated: {filename}")

if __name__ == "__main__":

# User input

emp_id = input("Enter Employee ID: ")

name = input("Enter Name: ")

designation = input("Enter Designation: ")

basic_salary = float(input("Enter Basic Salary: "))

work_days = int(input("Enter Work Days (out of 30): "))

deductions = float(input("Enter Deductions: "))

emp = Employee(emp_id, name, designation, basic_salary)

payslip = Payslip(emp, work_days, deductions)

payslip.generate_payslip()

OUTPUT:-

8) import os

class Complaint:

def __init__(self, complaint_id, description, status="OPEN"):

self.complaint_id = complaint_id

[Link] = description

[Link] = status

def __str__(self):

return f"ID: {self.complaint_id} | {[Link]} | Status: {[Link]}"

class ComplaintSystem:

def __init__(self, file_name="[Link]"):

self.file_name = file_name

[Link] = []
self.load_complaints()

def load_complaints(self):

if [Link](self.file_name):

with open(self.file_name, "r") as f:

for line in f:

parts = [Link]().split("|")

if len(parts) == 3:

cid, desc, status = parts

[Link](Complaint(int(cid), desc, status))

def save_complaints(self):

with open(self.file_name, "w") as f:

for c in [Link]:

[Link](f"{c.complaint_id}|{[Link]}|{[Link]}\n")

def get_next_id(self):

return max([c.complaint_id for c in [Link]], default=0) + 1

def register_complaint(self, description):

cid = self.get_next_id()

complaint = Complaint(cid, description)

[Link](complaint)

self.save_complaints()

print(f"✅ Complaint registered with ID {cid}")

def view_all_complaints(self):

if not [Link]:

print("No complaints found.")

else:

for c in [Link]:

print(c)

def view_open_complaints(self):

open_complaints = [c for c in [Link] if [Link] == "OPEN"]

if not open_complaints:

print("No open complaints.")

else:

for c in open_complaints:

print(c)

def search_by_id(self, complaint_id):

for c in [Link]:

if c.complaint_id == complaint_id:

print(c)

return c

print("❌ Complaint not found.")

return None

def mark_as_resolved(self, complaint_id):

for c in [Link]:
if c.complaint_id == complaint_id:

if [Link] == "RESOLVED":

print("Complaint is already resolved.")

else:

[Link] = "RESOLVED"

self.save_complaints()

print(f"✅ Complaint ID {complaint_id} marked as RESOLVED")

return

print("❌ Complaint not found.")

if __name__ == "__main__":

system = ComplaintSystem()

while True:

print("\n--- Complaint Management System ---")

print("1. Register Complaint")

print("2. View All Complaints")

print("3. View Open Complaints")

print("4. Search by ID")

print("5. Mark as Resolved")

print("6. Exit")

choice = input("Enter your choice: ")

if choice == "1":

desc = input("Enter complaint description: ")

system.register_complaint(desc)

elif choice == "2":

system.view_all_complaints()

elif choice == "3":

system.view_open_complaints()

elif choice == "4":

cid = int(input("Enter complaint ID: "))

system.search_by_id(cid)

elif choice == "5":

cid = int(input("Enter complaint ID to resolve: "))

system.mark_as_resolved(cid)

elif choice == "6":

print("Exiting system...")

break

else:

print("Invalid choice. Try again.")


OUTPUT:-

9) import os

class Student:

def __init__(self, student_id, name):

self.student_id = student_id

[Link] = name

def __str__(self):

return f"{self.student_id} - {[Link]}"

class Course:

def __init__(self, course_id, name, max_capacity):

self.course_id = course_id

[Link] = name

self.max_capacity = max_capacity

[Link] = [] # store student IDs

def is_full(self):

return len([Link]) >= self.max_capacity

def add_student(self, student_id):

if not self.is_full() and student_id not in [Link]:

[Link](student_id)

return True

return False

def __str__(self):

return f"{self.course_id} - {[Link]} (Capacity {len([Link])}/{self.max_capacity})"


class RegistrationSystem:

def __init__(self, file_name="[Link]"):

[Link] = {}

[Link] = {}

self.file_name = file_name

self.load_registrations()

def add_student(self, student_id, name):

if student_id not in [Link]:

[Link][student_id] = Student(student_id, name)

print(f"✅ Student {name} added.")

else:

print("❌ Student ID already exists.")

def add_course(self, course_id, name, max_capacity):

if course_id not in [Link]:

[Link][course_id] = Course(course_id, name, max_capacity)

print(f"✅ Course {name} added.")

else:

print("❌ Course ID already exists.")

def register_student(self, student_id, course_id):

if student_id not in [Link]:

print("❌ Student not found.")

return

if course_id not in [Link]:

print("❌ Course not found.")

return

course = [Link][course_id]

if course.is_full():

print("❌ Course is full.")

return

if course.add_student(student_id):

self.save_registrations()

print(f"✅ {[Link][student_id].name} registered for {[Link]}")

else:

print("❌ Student already registered in this course.")

def view_courses(self):

for course in [Link]():

print(course)

def view_students_in_course(self, course_id):

if course_id not in [Link]:

print("❌ Course not found.")

return

course = [Link][course_id]

if not [Link]:

print("No students enrolled yet.")


else:

print(f"Students in {[Link]}:")

for sid in [Link]:

print(f" - {[Link][sid]}")

def save_registrations(self):

with open(self.file_name, "w") as f:

for cid, course in [Link]():

for sid in [Link]:

[Link](f"{sid}|{cid}\n")

def load_registrations(self):

if [Link](self.file_name):

with open(self.file_name, "r") as f:

for line in f:

sid, cid = [Link]().split("|")

if cid in [Link] and sid not in [Link][cid].students:

[Link][cid].[Link](sid)

if __name__ == "__main__":

system = RegistrationSystem()

system.add_student("S1", "Alice")

system.add_student("S2", "Bob")

system.add_student("S3", "Charlie")

system.add_course("C101", "Python Programming", 2)

system.add_course("C102", "Data Structures", 3)

system.register_student("S1", "C101")

system.register_student("S2", "C101")

system.register_student("S3", "C101") # Should fail (course full)

system.register_student("S3", "C102")

print("\n--- Course List ---")

system.view_courses()

print("\n--- Students in Python Programming ---")

system.view_students_in_course("C101")

OUTPUT:-
10) import os

class Product:

def __init__(self, name, quantity, price):

[Link] = name

[Link] = quantity

[Link] = price

def __str__(self):

return f"{[Link]} | Qty: {[Link]} | Price: {[Link]:.2f}"

class InventorySystem:

def __init__(self, file_name="[Link]", threshold=5):

self.file_name = file_name

[Link] = threshold

[Link] = {}

self.load_inventory()

def load_inventory(self):

if [Link](self.file_name):

with open(self.file_name, "r") as f:

for line in f:

parts = [Link]().split("|")

if len(parts) == 3:

name, qty, price = parts

[Link][name] = Product(name, int(qty), float(price))

def save_inventory(self):

with open(self.file_name, "w") as f:

for p in [Link]():

[Link](f"{[Link]}|{[Link]}|{[Link]}\n")

def add_product(self, name, quantity, price):

if name in [Link]:

print("❌ Product already exists. Use update instead.")

else:

[Link][name] = Product(name, quantity, price)

self.save_inventory()

print(f"✅ Product {name} added.")

def update_product(self, name, quantity=None, price=None):

if name not in [Link]:

print("❌ Product not found.")

return

if quantity is not None:

[Link][name].quantity = quantity

if price is not None:

[Link][name].price = price

self.save_inventory()
print(f"✅ Product {name} updated.")

def delete_product(self, name):

if name in [Link]:

del [Link][name]

self.save_inventory()

print(f"✅ Product {name} deleted.")

else:

print("❌ Product not found.")

def list_products(self):

if not [Link]:

print("No products in inventory.")

else:

print("\n--- Inventory List ---")

for p in [Link]():

alert = " LOW STOCK" if [Link] < [Link] else ""

print(f"{p} {alert}")

def check_threshold(self):

low_stock = [p for p in [Link]() if [Link] < [Link]]

if not low_stock:

print("All products are sufficiently stocked.")

else:

print("\n Low Stock Alerts:")

for p in low_stock:

print(f"{p}")

if __name__ == "__main__":

inventory = InventorySystem()

while True:

print("\n--- Inventory Management ---")

print("1. Add Product")

print("2. Update Product")

print("3. Delete Product")

print("4. List Products")

print("5. Check Low Stock")

print("6. Exit")

choice = input("Enter your choice: ")

if choice == "1":

name = input("Enter product name: ")

qty = int(input("Enter quantity: "))

price = float(input("Enter price: "))

inventory.add_product(name, qty, price)

elif choice == "2":

name = input("Enter product name: ")

qty = input("Enter new quantity (leave blank to skip): ")


price = input("Enter new price (leave blank to skip): ")

qty = int(qty) if qty else None

price = float(price) if price else None

inventory.update_product(name, qty, price)

elif choice == "3":

name = input("Enter product name to delete: ")

inventory.delete_product(name)

elif choice == "4":

inventory.list_products()

elif choice == "5":

inventory.check_threshold()

elif choice == "6":

print("Exiting system...")

break

else:

print("Invalid choice. Try again.")

OUTPUT:-

Common questions

Powered by AI

The systems utilize capacity constraints to prevent overcapacity; the library limits book borrowing to availability, and the registration system restricts student enrollment based on predefined course capacities. These mechanisms ensure system stability by avoiding overloads that would lead to inefficient resource management. They maintain equilibrium in resource allocation, preventing the degradation of system performance or user experience due to excess demand .

Data redundancy arises in systems without efficient data management protocols where duplicate data entries occur, potentially leading to inconsistencies. In these systems, redundancy could be mitigated by implementing shared data modules with centralized storage - reducing duplication. Ensuring unique constraints, auditing mechanisms, and integrating database systems with normalization techniques are critical steps to mitigate redundancy by ensuring data integrity and coherence across the system .

Although the document does not explicitly mention authentication, it implicitly relies on user identification (e.g., user IDs) for book borrowing and complaint management, enhancing security by ensuring that only valid users perform actions on their behalf. Effective authentication and verification processes are critical for system reliability as they prevent unauthorized access, data breaches, and ensure that actions are traceably linked to legitimate users, enhancing both security and data integrity .

File operations ensure that data persists beyond the application's runtime in both library and complaint management systems by saving and loading data such as books, complaints, and user interactions. This persistence is crucial for retaining system state, such as the list of books or open complaints, across sessions, enabling consistent user experience and operational continuity. Without such operations, data would be lost upon shutdown, nullifying progress .

The availability of books directly impacts the user's ability to borrow. If a book is available, it can be borrowed, which then changes its status to 'issued'. Conversely, if a book is already issued, the user cannot borrow it until it is returned, hence maintaining the balance in book availability. This functionality ensures that a book cannot be double-borrowed and manages book circulation effectively .

The inventory management system provides user feedback for various operations, such as notifying if a product exists before updating and confirming successful actions. Error messages guide users to correct entries, such as indicating when products are not found. By offering immediate feedback and corrective guidance, the design enhances usability, preventing user frustration, reducing errors, and ensuring accurate data input .

Status updates in the complaint management system, such as marking complaints as 'OPEN' or 'RESOLVED', are crucial for tracking the progress and resolution of issues. Timely updates ensure that complaints are actively managed, allowing organizations to address customer concerns efficiently. This enhances communication transparency and improves customer satisfaction by demonstrating organizational responsiveness and accountability .

The SecureNote utilizes two encryption methods, Caesar cipher and Base64, allowing users to secure their notes with a chosen method. This choice provides flexibility and demonstrates an understanding of different levels of security needs. Each method's use reflects elementary to more complex encryption, with Caesar being a basic character shift and Base64 encoding data in a transferable format, illustrating varied approaches to data protection .

Course capacity determines the maximum number of students that can be enrolled in a course. If a course's capacity is reached, it becomes 'full', preventing further registrations. This ensures that courses do not exceed their limits, maintaining manageable class sizes and resource allocation. Attempts to register additional students in full courses result in registration denial .

The complaint registration system generates unique identifiers using a sequential increment strategy, which ensures each complaint has a distinct reference. This uniqueness is critical for tracking and managing issues accurately, preventing conflicts or ambiguities in records, and enabling precise reference for status updates and resolution processes, thereby enhancing data integrity and management efficiency .

You might also like