0% found this document useful (0 votes)
5 views

Python CO 4 ASSIGNMENT

The document outlines several Python programming assignments, including file handling with exception management, string formatting, a student management system, a banking system, and a library management system. Each section provides code examples and a menu-driven interface for user interaction. The assignments demonstrate the use of classes, file operations, and data persistence using the pickle module.

Uploaded by

2210031
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python CO 4 ASSIGNMENT

The document outlines several Python programming assignments, including file handling with exception management, string formatting, a student management system, a banking system, and a library management system. Each section provides code examples and a menu-driven interface for user interaction. The assignments demonstrate the use of classes, file operations, and data persistence using the pickle module.

Uploaded by

2210031
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python CO – 4 Assignment Karann S

2210031

1. File Creation, Reading, Writing with Exception Handling & Menu-Based System

import os

def create_file():

filename = input("Enter filename: ")

content = input("Enter content for the file: ")

try:

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

file.write(content)

print("File created successfully!")

except Exception as e:

print(f"Error: {e}")

def read_file():

filename = input("Enter filename to read: ")

try:

with open(filename, "r") as file:

print("File content:\n", file.read())

except FileNotFoundError:

print("Error: File not found.")

except PermissionError:

print("Error: Permission denied.")

except Exception as e:

print(f"Error: {e}")

def write_to_file():

filename = input("Enter filename to write to: ")


content = input("Enter content to append: ")

try:

with open(filename, "a") as file:

file.write("\n" + content)

print("Content written successfully!")

except Exception as e:

print(f"Error: {e}")

def main():

while True:

print("\nMenu:")

print("1. Create a File")

print("2. Read a File")

print("3. Write to a File")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":

create_file()

elif choice == "2":

read_file()

elif choice == "3":

write_to_file()

elif choice == "4":

print("Exiting...")

break

else:

print("Invalid choice! Try again.")

if __name__ == "__main__":

main()
2. String Formatting in Python:

# Using % Operator

name = "Alice"

age = 25

print("Hello, %s! You are %d years old." % (name, age))

# Using .format() Method

print("Hello, {}! You are {} years old.".format(name, age))

print("Hello, {1}! You are {0} years old.".format(age, name))

# Using f-strings

print(f"Hello, {name}! You are {age} years old.")

3.Student Management System Using Python Packages

student_management/

Project Structure:

│── __init__.py

│── student.py

│── database.py

│── main.py

(Student Class):

class Student:

def __init__(self, name, roll_no):

self.name = name

self.roll_no = roll_no
def __str__(self):

return f"Roll No: {self.roll_no}, Name: {self.name}"

(Handling Student Data):

import pickle

STUDENT_FILE = "students.dat"

def save_students(students):

with open(STUDENT_FILE, "wb") as file:

pickle.dump(students, file)

def load_students():

try:

with open(STUDENT_FILE, "rb") as file:

return pickle.load(file)

except FileNotFoundError:

return []

(Main Program):

from student_management.student import Student

from student_management.database import save_students, load_students

students = load_students()

def add_student():

name = input("Enter student name: ")

roll_no = input("Enter roll number: ")


students.append(Student(name, roll_no))

save_students(students)

print("Student added successfully!")

def display_students():

if not students:

print("No students found.")

else:

for student in students:

print(student)

def remove_student():

roll_no = input("Enter roll number to remove: ")

global students

students = [s for s in students if s.roll_no != roll_no]

save_students(students)

print("Student removed successfully!")

def main():

while True:

print("\nStudent Management System")

print("1. Add Student")

print("2. Display Students")

print("3. Remove Student")

print("4. Exit")

choice = input("Enter choice: ")


if choice == "1":

add_student()

elif choice == "2":

display_students()

elif choice == "3":

remove_student()

elif choice == "4":

print("Exiting...")

break

else:

print("Invalid choice!")

if __name__ == "__main__":

main()

4. Banking System Using Python Packages:

banking_system/

│── __init__.py

│── account.py

│── database.py

│── main.py

class Account:

def __init__(self, name, acc_no, balance=0):

self.name = name

self.acc_no = acc_no
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:

print("Insufficient balance!")

else:

self.balance -= amount

print(f"Withdrawn {amount}. New Balance: {self.balance}")

def __str__(self):

return f"Account No: {self.acc_no}, Name: {self.name}, Balance: {self.balance}"

import pickle

BANK_FILE = "accounts.dat"

def save_accounts(accounts):

with open(BANK_FILE, "wb") as file:

pickle.dump(accounts, file)

def load_accounts():

try:

with open(BANK_FILE, "rb") as file:


return pickle.load(file)

except FileNotFoundError:

return []

from banking_system.account import Account

from banking_system.database import save_accounts, load_accounts

accounts = load_accounts()

def create_account():

name = input("Enter account holder name: ")

acc_no = input("Enter account number: ")

accounts.append(Account(name, acc_no))

save_accounts(accounts)

print("Account created!")

def deposit_money():

acc_no = input("Enter account number: ")

amount = float(input("Enter amount to deposit: "))

for acc in accounts:

if acc.acc_no == acc_no:

acc.deposit(amount)

save_accounts(accounts)

return

print("Account not found!")

def withdraw_money():
acc_no = input("Enter account number: ")

amount = float(input("Enter amount to withdraw: "))

for acc in accounts:

if acc.acc_no == acc_no:

acc.withdraw(amount)

save_accounts(accounts)

return

print("Account not found!")

def display_accounts():

for acc in accounts:

print(acc)

def main():

while True:

print("\nBanking System")

print("1. Create Account")

print("2. Deposit Money")

print("3. Withdraw Money")

print("4. Display Accounts")

print("5. Exit")

choice = input("Enter choice: ")

if choice == "1":

create_account()

elif choice == "2":


deposit_money()

elif choice == "3":

withdraw_money()

elif choice == "4":

display_accounts()

elif choice == "5":

print("Exiting...")

break

else:

print("Invalid choice!")

if __name__ == "__main__":

main()

5. Library Management System Using Python Namespaces:

class Library:

def __init__(self):

self.books = []

def add_book(self, book):

self.books.append(book)

print("Book added successfully!")

def remove_book(self, book):

if book in self.books:

self.books.remove(book)

print("Book removed successfully!")


else:

print("Book not found!")

def search_book(self, book):

print("Book found!" if book in self.books else "Book not found!")

def display_books(self):

print("Available Books:", ", ".join(self.books) if self.books else "No books available.")

library = Library()

library.add_book("Python Basics")

library.display_books()

library.search_book("Python Basics")

library.remove_book("Python Basics")

library.display_books()

You might also like