Hostel Management System using Python
Python Project: Hostel Management System with Source Code
Namaste, dosto! Welcome to this mega, super-duper exciting blog post where we’re going to build a Hostel Management System using Python. This isn’t just any project—it’s a full-blown system to manage everything in a hostel, from student registrations to room allocations, fee payments, complaints, and even visitor tracking. We’re talking about a proper, practical application that could run a real hostel, all coded in Python with a desi twist. Whether you’re a student looking for a killer college project, a beginner dipping your toes into Python, or just someone who loves building cool stuff, this is for you. So, grab your laptop, maybe a plate of pakoras, and let’s dive into this Python adventure!
Why Build a Hostel Management System?
Arre, before we start typing code, let’s chat about why this project is such a fantastic idea. Hostels are like second homes for students, right? Whether it’s a college hostel, a PG, or a private hostel, there’s always a warden or manager juggling a million things—keeping track of students, assigning rooms, collecting fees, handling complaints, and making sure no random visitor sneaks in. Doing all this with pen and paper? Uff, that’s a nightmare! Our Hostel Management System is like a magic wand—it automates everything, making life easy for hostel admins and students alike.
This project is perfect for:
- Students: Need a solid final-year project to impress your professor? This is a winner.
- Beginners: New to Python? You’ll learn variables, functions, databases, and more in a fun way.
- Developers: Want to build a real-world app? This can be scaled to a web or mobile app later.
We’re using Python because it’s simple, powerful, and has awesome libraries to make coding a breeze. We’ll also use SQLite for storing data and keep the interface console-based to keep things beginner-friendly. By the end, you’ll have a complete system with source code you can run yourself. Chalo, let’s get started!
Project Overview
Our Hostel Management System will have all the features a modern hostel needs. Here’s what we’re building:
- Student Management: Register students, update their details, remove them, or view their info.
- Room Management: Add rooms, assign them to students, update room details, or mark them as vacant.
- Fee Management: Track fee payments, calculate pending dues, and generate payment receipts.
- Complaint System: Allow students to log complaints (like a leaky tap or a noisy roommate) and track their status.
- Visitor Tracking: Record visitor details and their entry/exit times.
- Search Functionality: Search for students, rooms, or complaints using keywords.
- Reports: Generate reports like occupied rooms, pending fees, or unresolved complaints.
- Console Interface: A simple text-based menu to interact with the system (we’ll talk about GUI upgrades later).
- Database Integration: Use SQLite to store all data securely and efficiently.
We’ll code this in Python 3.x, use SQLite for the database, and keep it simple with a console interface. The source code will be included, so you can copy-paste and run it. We’ll break it down step-by-step, explaining everything like I’m your coding bhai, sitting right next to you with a samosa in hand.
Tools and Technologies
Before we start, let’s gather our tools—like packing your bag before moving into a hostel! Here’s what you need:
- Python 3.x: Make sure Python is installed. Download it from python.org if you don’t have it.
- SQLite: A lightweight database that comes built-in with Python—no extra installation needed.
- Text Editor/IDE: Use VS Code, PyCharm, or even Notepad++ (whatever you’re comfortable with, yaar).
- Basic Python Knowledge: You should know variables, loops, functions, and maybe a bit about classes. Don’t worry, we’ll explain everything!
- Python Libraries: We’ll use
sqlite3
for the database,datetime
for handling dates, anduuid
for unique IDs. No external libraries, so it’s super easy to set up.
If you don’t have Python installed, go to python.org, download the latest version, and install it. SQLite is already part of Python, so no tension there. Alright, let’s set up the project structure!
Project Setup
First, create a folder for our project. Call it HostelManagementSystem
or something cool like DesiHostelApp
. Inside this folder, create a Python file called hostel.py
. This will be our main file where all the action happens. Here’s how your folder should look:
HostelManagementSystem/
├── hostel.py
├── hostel.db (this will be created automatically by SQLite)
No need for extra files yet—we’ll keep it simple. Open hostel.py
in your text editor, and let’s start coding. We’ll build this system step-by-step, starting with the database, then adding features one by one. Each section will have explanations, code, and examples, so you won’t feel lost, bhai.
Setting Up the Database
Since we’re using SQLite, we need a database to store all our data. We’ll create four main tables:
- Students: To store student details like name, contact info, and student ID.
- Rooms: To store room details like room number, capacity, and status (occupied or vacant).
- Fees: To track fee payments, including amount paid and pending dues.
- Complaints: To log student complaints and their resolution status.
- Visitors: To record visitor details and their entry/exit times.
Let’s write the code to create these tables. Open hostel.py
and add this:
import sqlite3
from datetime import datetime, timedelta
import uuid
# Connect to SQLite database (creates a new database if it doesn't exist)
def init_db():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
# Create Students table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
student_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
phone TEXT,
address TEXT,
join_date TEXT
)
''')
# Create Rooms table
cursor.execute('''
CREATE TABLE IF NOT EXISTS rooms (
room_id TEXT PRIMARY KEY,
room_number TEXT UNIQUE NOT NULL,
capacity INTEGER NOT NULL,
status TEXT DEFAULT 'Vacant',
student_id TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Fees table
cursor.execute('''
CREATE TABLE IF NOT EXISTS fees (
fee_id TEXT PRIMARY KEY,
student_id TEXT,
amount_due REAL NOT NULL,
amount_paid REAL DEFAULT 0.0,
payment_date TEXT,
due_date TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Complaints table
cursor.execute('''
CREATE TABLE IF NOT EXISTS complaints (
complaint_id TEXT PRIMARY KEY,
student_id TEXT,
description TEXT NOT NULL,
status TEXT DEFAULT 'Pending',
complaint_date TEXT,
resolution_date TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Visitors table
cursor.execute('''
CREATE TABLE IF NOT EXISTS visitors (
visitor_id TEXT PRIMARY KEY,
student_id TEXT,
visitor_name TEXT NOT NULL,
entry_time TEXT,
exit_time TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
conn.commit()
conn.close()
print("Database initialized successfully! Sab set hai, bhai!")
# Initialize the database when the script runs
if __name__ == "__main__":
init_db()
Explanation
- We import
sqlite3
for database operations,datetime
andtimedelta
for handling dates, anduuid
for generating unique IDs. - The
init_db()
function connects tohostel.db
(it’ll create the file automatically if it doesn’t exist). - We create five tables:
- Students: Stores student details with a unique
student_id
, name, email, phone, address, and join date. - Rooms: Stores room details like
room_id
, room number, capacity, status, and thestudent_id
of the occupant (if any). - Fees: Tracks fee payments with
fee_id
,student_id
, amount due, amount paid, payment date, and due date. - Complaints: Logs complaints with
complaint_id
,student_id
, description, status, complaint date, and resolution date. - Visitors: Records visitor details with
visitor_id
,student_id
, visitor name, entry time, and exit time.
- Students: Stores student details with a unique
- The
FOREIGN KEY
constraints ensure data integrity (e.g., a room can only be assigned to a valid student). - When you run this code, it creates
hostel.db
and prints a success message.
Run this code, and you’ll see hostel.db
in your folder. You can open it with an SQLite viewer (like DB Browser for SQLite) to check the tables. Now, let’s add functions to manage students!
Managing Students
Let’s create functions to add, update, delete, and view student details. These are the core operations for managing hostel residents. Add this to hostel.py
:
# Add a new student
def add_student(name, email, phone, address):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
student_id = str(uuid.uuid4())
join_date = datetime.now().strftime("%Y-%m-%d")
try:
cursor.execute('''
INSERT INTO students (student_id, name, email, phone, address, join_date)
VALUES (?, ?, ?, ?, ?, ?)
''', (student_id, name, email, phone, address, join_date))
conn.commit()
print(f"Student '{name}' added successfully with ID: {student_id}. Welcome to the hostel!")
底下
except sqlite3.IntegrityError:
print("Arre, error! A student with this email already exists!")
finally:
conn.close()
# Update student details
def update_student(student_id, name=None, email=None, phone=None, address=None):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
updates = {}
if name:
updates['name'] = name
if email:
updates['email'] = email
if phone:
updates['phone'] = phone
if address:
updates['address'] = address
if updates:
query = "UPDATE students SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE student_id = ?"
values = list(updates.values()) + [student_id]
cursor.execute(query, values)
conn.commit()
print(f"Student with ID {student_id} updated successfully! Sab set hai!")
else:
print("Kuch nahi diya to update kya karu?")
conn.close()
# Delete a student
def delete_student(student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM rooms WHERE student_id = ?", (student_id,))
occupied_room = cursor.fetchone()
if occupied_room:
print("Arre, error! Cannot delete student because they are assigned to a room!")
else:
cursor.execute("DELETE FROM students WHERE student_id = ?", (student_id,))
conn.commit()
print(f"Student with ID {student_id} deleted successfully! Bye-bye!")
conn.close()
# View student details
def view_student(student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if student:
print(f"\nStudent Details:\nID: {student[0]}\nName: {student[1]}\nEmail: {student[2]}\nPhone: {student[3]}\nAddress: {student[4]}\nJoin Date: {student[5]}")
else:
print("Oops, student not found, bhai!")
conn.close()
# Test the student management functions
if __name__ == "__main__":
init_db()
add_student("Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi")
view_student("some-student-id")
update_student("some-student-id", name="Rahul Kumar")
delete_student("some-student-id")
Explanation
- Add Student: Generates a unique
student_id
, records the join date, and adds the student to thestudents
table. It checks for duplicate emails. - Update Student: Updates specific fields (name, email, phone, address) for a student using their
student_id
. - Delete Student: Checks if the student is assigned to a room before deleting to avoid orphaned data.
- View Student: Displays a student’s details by their
student_id
. - The test code adds a student, views their details, updates their name, and tries to delete them (replace "some-student-id" with an actual ID).
Managing Rooms
Now, let’s handle room management—adding rooms, assigning them to students, updating details, and marking them as vacant. Add this to hostel.py
:
# Add a new room
def add_room(room_number, capacity):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
room_id = str(uuid.uuid4())
try:
cursor.execute('''
INSERT INTO rooms (room_id, room_number, capacity, status)
VALUES (?, ?, ?, ?)
''', (room_id, room_number, capacity, 'Vacant'))
conn.commit()
print(f"Room {room_number} added successfully with ID: {room_id}. Ready for occupants!")
except sqlite3.IntegrityError:
print("Arre, error! A room with this number already exists!")
finally:
conn.close()
# Assign a room to a student
def assign_room(room_id, student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT status FROM rooms WHERE room_id = ?", (room_id,))
room = cursor.fetchone()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not room:
print("Arre, room nahi mila!")
conn.close()
return
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
if room[0] != 'Vacant':
print("Sorry, room already occupied hai!")
conn.close()
return
cursor.execute("UPDATE rooms SET status = 'Occupied', student_id = ? WHERE room_id = ?", (student_id, room_id))
conn.commit()
print(f"Room assigned successfully to student ID {student_id}!")
conn.close()
# Update room details
def update_room(room_id, room_number=None, capacity=None):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
updates = {}
if room_number:
updates['room_number'] = room_number
if capacity:
updates['capacity'] = capacity
if updates:
query = "UPDATE rooms SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE room_id = ?"
values = list(updates.values()) + [room_id]
cursor.execute(query, values)
conn.commit()
print(f"Room with ID {room_id} updated successfully! Sab set hai!")
else:
print("Kuch nahi diya to update kya karu?")
conn.close()
# Mark a room as vacant
def vacate_room(room_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM rooms WHERE room_id = ?", (room_id,))
room = cursor.fetchone()
if not room:
print("Arre, room nahi mila!")
else:
cursor.execute("UPDATE rooms SET status = 'Vacant', student_id = NULL WHERE room_id = ?", (room_id,))
conn.commit()
print(f"Room {room_id} is now vacant! Ready for a new occupant!")
conn.close()
# Test room management functions
if __name__ == "__main__":
init_db()
add_room("101", 2)
add_student("Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi")
assign_room("some-room-id", "some-student-id")
update_room("some-room-id", room_number="102")
vacate_room("some-room-id")
Explanation
- Add Room: Adds a new room with a unique
room_id
, room number, capacity, and sets status to "Vacant". - Assign Room: Assigns a room to a student if it’s vacant and the student exists.
- Update Room: Updates room number or capacity for a room using its
room_id
. - Vacate Room: Marks a room as vacant and removes the student assignment.
- The test code adds a room, assigns it, updates it, and vacates it (replace IDs with actual ones).
Managing Fees
Let’s handle fee payments—tracking dues, recording payments, and generating receipts. Add this to hostel.py
:
# Add a fee record
def add_fee(student_id, amount_due):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
fee_id = str(uuid.uuid4())
due_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
cursor.execute('''
INSERT INTO fees (fee_id, student_id, amount_due, due_date sarvshreshth
VALUES (?, ?, ?, ?)
''', (fee_id, student_id, amount_due, due_date))
conn.commit()
print(f"Fee record added for student ID {student_id}. Amount due: Rs. {amount_due}, Due Date: {due_date}")
conn.close()
# Record a fee payment
def record_payment(fee_id, amount_paid):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT amount_due, amount_paid FROM fees WHERE fee_id = ?", (fee_id,))
fee = cursor.fetchone()
if not fee:
print("Arre, fee record nahi mila!")
conn.close()
return
amount_due, current_paid = fee
new_paid = current_paid + amount_paid
payment_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
UPDATE fees
SET amount_paid = ?, payment_date = ?
WHERE fee_id = ?
''', (new_paid, payment_date, fee_id))
conn.commit()
if new_paid >= amount_due:
print(f"Payment of Rs. {amount_paid} recorded successfully! Fee fully paid!")
else:
print(f"Payment of Rs. {amount_paid} recorded successfully! Pending: Rs. {amount_due - new_paid}")
conn.close()
# View pending fees
def view_pending_fees():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT f.fee_id, s.name, f.amount_due, f.amount_paid, f.due_date
FROM fees f
JOIN students s ON f.student_id = s.student_id
WHERE f.amount_paid < f.amount_due
''')
fees = cursor.fetchall()
if fees:
print("\nPending Fees:")
for f in fees:
print(f"Fee ID: {f[0]}, Student: {f[1]}, Due: Rs. {f[2]}, Paid: Rs. {f[3]}, Due Date: {f[4]}")
else:
print("Koi pending fees nahi hai, sab paid hai!")
conn.close()
# Test fee management functions
if __name__ == "__main__":
init_db()
add_student("Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi")
add_fee("some-student-id", 5000.0)
record_payment("some-fee-id", 3000.0)
view_pending_fees()
Explanation
- Add Fee: Creates a fee record for a student with an amount due and a 30-day due date.
- Record Payment: Updates the paid amount and records the payment date. Checks if the fee is fully paid.
- View Pending Fees: Shows all fee records where the amount paid is less than the amount due.
- The test code adds a fee, records a partial payment, and views pending fees.
Managing Complaints
Let’s allow students to log complaints and track their resolution. Add this to hostel.py
:
# Log a complaint
def log_complaint(student_id, description):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
complaint_id = str(uuid.uuid4())
complaint_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
INSERT INTO complaints (complaint_id, student_id, description, complaint_date)
VALUES (?, ?, ?, ?)
''', (complaint_id, student_id, description, complaint_date))
conn.commit()
print(f"Complaint logged successfully! Complaint ID: {complaint_id}")
conn.close()
# Resolve a complaint
def resolve_complaint(complaint_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM complaints WHERE complaint_id = ? AND status = 'Pending'", (complaint_id,))
complaint = cursor.fetchone()
if not complaint:
print("Arre, complaint nahi mila or already resolved hai!")
conn.close()
return
resolution_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
UPDATE complaints
SET status = 'Resolved', resolution_date = ?
WHERE complaint_id = ?
''', (resolution_date, complaint_id))
conn.commit()
print(f"Complaint {complaint_id} resolved successfully!")
conn.close()
# View pending complaints
def view_pending_complaints():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT c.complaint_id, s.name, c.description, c.complaint_date
FROM complaints c
JOIN students s ON c.student_id = s.student_id
WHERE c.status = 'Pending'
''')
complaints = cursor.fetchall()
if complaints:
print("\nPending Complaints:")
for c in complaints:
print(f"Complaint ID: {c[0]}, Student: {c[1]}, Description: {c[2]}, Date: {c[3]}")
else:
print("Koi pending complaints nahi hai!")
conn.close()
# Test complaint management functions
if __name__ == "__main__":
init_db()
add_student("Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi")
log_complaint("some-student-id", "Leaky tap in room 101")
resolve_complaint("some-complaint-id")
view_pending_complaints()
Explanation
- Log Complaint: Logs a complaint for a student with a description and date.
- Resolve Complaint: Marks a complaint as resolved and records the resolution date.
- View Pending Complaints: Shows all unresolved complaints with student details.
Managing Visitors
Let’s track visitors to the hostel. Add this to hostel.py
:
# Record a visitor
def record_visitor(student_id, visitor_name):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
visitor_id = str(uuid.uuid4())
entry_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
INSERT INTO visitors (visitor_id, student_id, visitor_name, entry_time)
VALUES (?, ?, ?, ?)
''', (visitor_id, student_id, visitor_name, entry_time))
conn.commit()
print(f"Visitor {visitor_name} recorded for student ID {student_id}!")
conn.close()
# Record visitor exit
def record_visitor_exit(visitor_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM visitors WHERE visitor_id = ? AND exit_time IS NULL", (visitor_id,))
visitor = cursor.fetchone()
if not visitor:
print("Arre, visitor nahi mila or already left hai!")
conn.close()
return
exit_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
UPDATE visitors
SET exit_time = ?
WHERE visitor_id = ?
''', (exit_time, visitor_id))
conn.commit()
print(f"Visitor exit recorded for visitor ID {visitor_id}!")
conn.close()
# View visitor log
def view_visitor_log():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT v.visitor_id, s.name, v.visitor_name, v.entry_time, v.exit_time
FROM visitors v
JOIN students s ON v.student_id = s.student_id
''')
visitors = cursor.fetchall()
if visitors:
print("\nVisitor Log:")
for v in visitors:
print(f"Visitor ID: {v[0]}, Student: {v[1]}, Visitor Name: {v[2]}, Entry: {v[3]}, Exit: {v[4]}")
else:
print("Koi visitors nahi hai abhi!")
conn.close()
# Test visitor management functions
if __name__ == "__main__":
init_db()
add_student("Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi")
record_visitor("some-student-id", "Vikram Singh")
record_visitor_exit("some-visitor-id")
view_visitor_log()
Explanation
- Record Visitor: Logs a visitor’s entry with their name and entry time.
- Record Visitor Exit: Updates the exit time for a visitor.
- View Visitor Log: Shows all visitor records with student details.
Creating a User Interface
To make the system user-friendly, let’s add a console-based menu. Add this to hostel.py
:
def main_menu():
while True:
print("\n=== Hostel Management System ===")
print("1. Add Student")
print("2. Update Student")
print("3. Delete Student")
print("4. View Student")
print("5. Add Room")
print("6. Assign Room")
print("7. Update Room")
print("8. Vacate Room")
print("9. Add Fee")
print("10. Record Payment")
print("11. View Pending Fees")
print("12. Log Complaint")
print("13. Resolve Complaint")
print("14. View Pending Complaints")
print("15. Record Visitor")
print("16. Record Visitor Exit")
print("17. View Visitor Log")
print("18. Exit")
choice = input("Enter your choice (1-18): ")
if choice == '1':
name = input("Enter student name: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")
address = input("Enter address: ")
add_student(name, email, phone, address)
elif choice == '2':
student_id = input("Enter student ID: ")
name = input("Enter new name (or press Enter to skip): ")
email = input("Enter new email (or press Enter to skip): ")
phone = input("Enter new phone (or press Enter to skip): ")
address = input("Enter new address (or press Enter to skip): ")
update_student(student_id, name or None, email or None, phone or None, address or None)
elif choice == '3':
student_id = input("Enter student ID to delete: ")
delete_student(student_id)
elif choice == '4':
student_id = input("Enter student ID to view: ")
view_student(student_id)
elif choice == '5':
room_number = input("Enter room number: ")
capacity = input("Enter room capacity: ")
add_room(room_number, int(capacity))
elif choice == '6':
room_id = input("Enter room ID: ")
student_id = input("Enter student ID: ")
assign_room(room_id, student_id)
elif choice == '7':
room_id = input("Enter room ID: ")
room_number = input("Enter new room number (or press Enter to skip): ")
capacity = input("Enter new capacity (or press Enter to skip): ")
update_room(room_id, room_number or None, int(capacity) if capacity else None)
elif choice == '8':
room_id = input("Enter room ID to vacate: ")
vacate_room(room_id)
elif choice == '9':
student_id = input("Enter student ID: ")
amount_due = input("Enter amount due: ")
add_fee(student_id, float(amount_due))
elif choice == '10':
fee_id = input("Enter fee ID: ")
amount_paid = input("Enter amount paid: ")
record_payment(fee_id, float(amount_paid))
elif choice == '11':
view_pending_fees()
elif choice == '12':
student_id = input("Enter student ID: ")
description = input("Enter complaint description: ")
log_complaint(student_id, description)
elif choice == '13':
complaint_id = input("Enter complaint ID: ")
resolve_complaint(complaint_id)
elif choice == '14':
view_pending_complaints()
elif choice == '15':
student_id = input("Enter student ID: ")
visitor_name = input("Enter visitor name: ")
record_visitor(student_id, visitor_name)
elif choice == '16':
visitor_id = input("Enter visitor ID: ")
record_visitor_exit(visitor_id)
elif choice == '17':
view_visitor_log()
elif choice == '18':
print("Thank you for using the Hostel Management System. Chalte hai ab!")
break
else:
print("Galat choice, bhai! Try again.")
if __name__ == "__main__":
init_db()
main_menu()
Explanation
- The
main_menu()
function shows a menu with 18 options and usesinput()
to get the user’s choice. - Based on the choice, it calls the appropriate function and collects necessary inputs.
- The loop runs until the user selects "Exit" (option 18).
Complete Source Code
Here’s the complete hostel.py
file with all the code combined:
import sqlite3
from datetime import datetime, timedelta
import uuid
# Connect to SQLite database (creates a new database if it doesn't exist)
def init_db():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
# Create Students table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
student_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
phone TEXT,
address TEXT,
join_date TEXT
)
''')
# Create Rooms table
cursor.execute('''
CREATE TABLE IF NOT EXISTS rooms (
room_id TEXT PRIMARY KEY,
room_number TEXT UNIQUE NOT NULL,
capacity INTEGER NOT NULL,
status TEXT DEFAULT 'Vacant',
student_id TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Fees table
cursor.execute('''
CREATE TABLE IF NOT EXISTS fees (
fee_id TEXT PRIMARY KEY,
student_id TEXT,
amount_due REAL NOT NULL,
amount_paid REAL DEFAULT 0.0,
payment_date TEXT,
due_date TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Complaints table
cursor.execute('''
CREATE TABLE IF NOT EXISTS complaints (
complaint_id TEXT PRIMARY KEY,
student_id TEXT,
description TEXT NOT NULL,
status TEXT DEFAULT 'Pending',
complaint_date TEXT,
resolution_date TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
# Create Visitors table
cursor.execute('''
CREATE TABLE IF NOT EXISTS visitors (
visitor_id TEXT PRIMARY KEY,
student_id TEXT,
visitor_name TEXT NOT NULL,
entry_time TEXT,
exit_time TEXT,
FOREIGN KEY (student_id) REFERENCES students (student_id)
)
''')
conn.commit()
conn.close()
print("Database initialized successfully! Sab set hai, bhai!")
# Add a new student
def add_student(name, email, phone, address):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
student_id = str(uuid.uuid4())
join_date = datetime.now().strftime("%Y-%m-%d")
try:
cursor.execute('''
INSERT INTO students (student_id, name, email, phone, address, join_date)
VALUES (?, ?, ?, ?, ?, ?)
''', (student_id, name, email, phone, address, join_date))
conn.commit()
print(f"Student '{name}' added successfully with ID: {student_id}. Welcome to the hostel!")
except sqlite3.IntegrityError:
print("Arre, error! A student with this email already exists!")
finally:
conn.close()
# Update student details
def update_student(student_id, name=None, email=None, phone=None, address=None):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
updates = {}
if name:
updates['name'] = name
if email:
updates['email'] = email
if phone:
updates['phone'] = phone
if address:
updates['address'] = address
if updates:
query = "UPDATE students SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE student_id = ?"
values = list(updates.values()) + [student_id]
cursor.execute(query, values)
conn.commit()
print(f"Student with ID {student_id} updated successfully! Sab set hai!")
else:
print("Kuch nahi diya to update kya karu?")
conn.close()
# Delete a student
def delete_student(student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM rooms WHERE student_id = ?", (student_id,))
occupied_room = cursor.fetchone()
if occupied_room:
print("Arre, error! Cannot delete student because they are assigned to a room!")
else:
cursor.execute("DELETE FROM students WHERE student_id = ?", (student_id,))
conn.commit()
print(f"Student with ID {student_id} deleted successfully! Bye-bye!")
conn.close()
# View student details
def view_student(student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if student:
print(f"\nStudent Details:\nID: {student[0]}\nName: {student[1]}\nEmail: {student[2]}\nPhone: {student[3]}\nAddress: {student[4]}\nJoin Date: {student[5]}")
else:
print("Oops, student not found, bhai!")
conn.close()
# Add a new room
def add_room(room_number, capacity):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
room_id = str(uuid.uuid4())
try:
cursor.execute('''
INSERT INTO rooms (room_id, room_number, capacity, status)
VALUES (?, ?, ?, ?)
''', (room_id, room_number, capacity, 'Vacant'))
conn.commit()
print(f"Room {room_number} added successfully with ID: {room_id}. Ready for occupants!")
except sqlite3.IntegrityError:
print("Arre, error! A room with this number already exists!")
finally:
conn.close()
# Assign a room to a student
def assign_room(room_id, student_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT status FROM rooms WHERE room_id = ?", (room_id,))
room = cursor.fetchone()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not room:
print("Arre, room nahi mila!")
conn.close()
return
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
if room[0] != 'Vacant':
print("Sorry, room already occupied hai!")
conn.close()
return
cursor.execute("UPDATE rooms SET status = 'Occupied', student_id = ? WHERE room_id = ?", (student_id, room_id))
conn.commit()
print(f"Room assigned successfully to student ID {student_id}!")
conn.close()
# Update room details
def update_room(room_id, room_number=None, capacity=None):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
updates = {}
if room_number:
updates['room_number'] = room_number
if capacity:
updates['capacity'] = capacity
if updates:
query = "UPDATE rooms SET " + ", ".join(f"{key} = ?" for key in updates.keys()) + " WHERE room_id = ?"
values = list(updates.values()) + [room_id]
cursor.execute(query, values)
conn.commit()
print(f"Room with ID {room_id} updated successfully! Sab set hai!")
else:
print("Kuch nahi diya to update kya karu?")
conn.close()
# Mark a room as vacant
def vacate_room(room_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM rooms WHERE room_id = ?", (room_id,))
room = cursor.fetchone()
if not room:
print("Arre, room nahi mila!")
else:
cursor.execute("UPDATE rooms SET status = 'Vacant', student_id = NULL WHERE room_id = ?", (room_id,))
conn.commit()
print(f"Room {room_id} is now vacant! Ready for a new occupant!")
conn.close()
# Add a fee record
def add_fee(student_id, amount_due):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
fee_id = str(uuid.uuid4())
due_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
cursor.execute('''
INSERT INTO fees (fee_id, student_id, amount_due, due_date)
VALUES (?, ?, ?, ?)
''', (fee_id, student_id, amount_due, due_date))
conn.commit()
print(f"Fee record added for student ID {student_id}. Amount due: Rs. {amount_due}, Due Date: {due_date}")
conn.close()
# Record a fee payment
def record_payment(fee_id, amount_paid):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT amount_due, amount_paid FROM fees WHERE fee_id = ?", (fee_id,))
fee = cursor.fetchone()
if not fee:
print("Arre, fee record nahi mila!")
conn.close()
return
amount_due, current_paid = fee
new_paid = current_paid + amount_paid
payment_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
UPDATE fees
SET amount_paid = ?, payment_date = ?
WHERE fee_id = ?
''', (new_paid, payment_date, fee_id))
conn.commit()
if new_paid >= amount_due:
print(f"Payment of Rs. {amount_paid} recorded successfully! Fee fully paid!")
else:
print(f"Payment of Rs. {amount_paid} recorded successfully! Pending: Rs. {amount_due - new_paid}")
conn.close()
# View pending fees
def view_pending_fees():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT f.fee_id, s.name, f.amount_due, f.amount_paid, f.due_date
FROM fees f
JOIN students s ON f.student_id = s.student_id
WHERE f.amount_paid < f.amount_due
''')
fees = cursor.fetchall()
if fees:
print("\nPending Fees:")
for f in fees:
print(f"Fee ID: {f[0]}, Student: {f[1]}, Due: Rs. {f[2]}, Paid: Rs. {f[3]}, Due Date: {f[4]}")
else:
print("Koi pending fees nahi hai, sab paid hai!")
conn.close()
# Log a complaint
def log_complaint(student_id, description):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
complaint_id = str(uuid.uuid4())
complaint_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
INSERT INTO complaints (complaint_id, student_id, description, complaint_date)
VALUES (?, ?, ?, ?)
''', (complaint_id, student_id, description, complaint_date))
conn.commit()
print(f"Complaint logged successfully! Complaint ID: {complaint_id}")
conn.close()
# Resolve a complaint
def resolve_complaint(complaint_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM complaints WHERE complaint_id = ? AND status = 'Pending'", (complaint_id,))
complaint = cursor.fetchone()
if not complaint:
print("Arre, complaint nahi mila or already resolved hai!")
conn.close()
return
resolution_date = datetime.now().strftime("%Y-%m-%d")
cursor.execute('''
UPDATE complaints
SET status = 'Resolved', resolution_date = ?
WHERE complaint_id = ?
''', (resolution_date, complaint_id))
conn.commit()
print(f"Complaint {complaint_id} resolved successfully!")
conn.close()
# View pending complaints
def view_pending_complaints():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT c.complaint_id, s.name, c.description, c.complaint_date
FROM complaints c
JOIN students s ON c.student_id = s.student_id
WHERE c.status = 'Pending'
''')
complaints = cursor.fetchall()
if complaints:
print("\nPending Complaints:")
for c in complaints:
print(f"Complaint ID: {c[0]}, Student: {c[1]}, Description: {c[2]}, Date: {c[3]}")
else:
print("Koi pending complaints nahi hai!")
conn.close()
# Record a visitor
def record_visitor(student_id, visitor_name):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
student = cursor.fetchone()
if not student:
print("Student nahi hai, bhai!")
conn.close()
return
visitor_id = str(uuid.uuid4())
entry_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
INSERT INTO visitors (visitor_id, student_id, visitor_name, entry_time)
VALUES (?, ?, ?, ?)
''', (visitor_id, student_id, visitor_name, entry_time))
conn.commit()
print(f"Visitor {visitor_name} recorded for student ID {student_id}!")
conn.close()
# Record visitor exit
def record_visitor_exit(visitor_id):
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM visitors WHERE visitor_id = ? AND exit_time IS NULL", (visitor_id,))
visitor = cursor.fetchone()
if not visitor:
print("Arre, visitor nahi mila or already left hai!")
conn.close()
return
exit_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
UPDATE visitors
SET exit_time = ?
WHERE visitor_id = ?
''', (exit_time, visitor_id))
conn.commit()
print(f"Visitor exit recorded for visitor ID {visitor_id}!")
conn.close()
# View visitor log
def view_visitor_log():
conn = sqlite3.connect('hostel.db')
cursor = conn.cursor()
cursor.execute('''
SELECT v.visitor_id, s.name, v.visitor_name, v.entry_time, v.exit_time
FROM visitors v
JOIN students s ON v.student_id = s.student_id
''')
visitors = cursor.fetchall()
if visitors:
print("\nVisitor Log:")
for v in visitors:
print(f"Visitor ID: {v[0]}, Student: {v[1]}, Visitor Name: {v[2]}, Entry: {v[3]}, Exit: {v[4]}")
else:
print("Koi visitors nahi hai abhi!")
conn.close()
def main_menu():
while True:
print("\n=== Hostel Management System ===")
print("1. Add Student")
print("2. Update Student")
print("3. Delete Student")
print("4. View Student")
print("5. Add Room")
print("6. Assign Room")
print("7. Update Room")
print("8. Vacate Room")
print("9. Add Fee")
print("10. Record Payment")
print("11. View Pending Fees")
print("12. Log Complaint")
print("13. Resolve Complaint")
print("14. View Pending Complaints")
print("15. Record Visitor")
print("16. Record Visitor Exit")
print("17. View Visitor Log")
print("18. Exit")
choice = input("Enter your choice (1-18): ")
if choice == '1':
name = input("Enter student name: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")
address = input("Enter address: ")
add_student(name, email, phone, address)
elif choice == '2':
student_id = input("Enter student ID: ")
name = input("Enter new name (or press Enter to skip): ")
email = input("Enter new email (or press Enter to skip): ")
phone = input("Enter new phone (or press Enter to skip): ")
address = input("Enter new address (or press Enter to skip): ")
update_student(student_id, name or None, email or None, phone or None, address or None)
elif choice == '3':
student_id = input("Enter student ID to delete: ")
delete_student(student_id)
elif choice == '4':
student_id = input("Enter student ID to view: ")
view_student(student_id)
elif choice == '5':
room_number = input("Enter room number: ")
capacity = input("Enter room capacity: ")
add_room(room_number, int(capacity))
elif choice == '6':
room_id = input("Enter room ID: ")
student_id = input("Enter student ID: ")
assign_room(room_id, student_id)
elif choice == '7':
room_id = input("Enter room ID: ")
room_number = input("Enter new room number (or press Enter to skip): ")
capacity = input("Enter new capacity (or press Enter to skip): ")
update_room(room_id, room_number or None, int(capacity) if capacity else None)
elif choice == '8':
room_id = input("Enter room ID to vacate: ")
vacate_room(room_id)
elif choice == '9':
student_id = input("Enter student ID: ")
amount_due = input("Enter amount due: ")
add_fee(student_id, float(amount_due))
elif choice == '10':
fee_id = input("Enter fee ID: ")
amount_paid = input("Enter amount paid: ")
record_payment(fee_id, float(amount_paid))
elif choice == '11':
view_pending_fees()
elif choice == '12':
student_id = input("Enter student ID: ")
description = input("Enter complaint description: ")
log_complaint(student_id, description)
elif choice == '13':
complaint_id = input("Enter complaint ID: ")
resolve_complaint(complaint_id)
elif choice == '14':
view_pending_complaints()
elif choice == '15':
student_id = input("Enter student ID: ")
visitor_name = input("Enter visitor name: ")
record_visitor(student_id, visitor_name)
elif choice == '16':
visitor_id = input("Enter visitor ID: ")
record_visitor_exit(visitor_id)
elif choice == '17':
view_visitor_log()
elif choice == '18':
print("Thank you for using the Hostel Management System. Chalte hai ab!")
break
else:
print("Galat choice, bhai! Try again.")
if __name__ == "__main__":
init_db()
main_menu()
Testing the System
To test the system, save the code in hostel.py
and run it (python hostel.py
). You’ll see the menu:
=== Hostel Management System ===
1. Add Student
2. Update Student
3. Delete Student
4. View Student
5. Add Room
6. Assign Room
7. Update Room
8. Vacate Room
9. Add Fee
10. Record Payment
11. View Pending Fees
12. Log Complaint
13. Resolve Complaint
14. View Pending Complaints
15. Record Visitor
16. Record Visitor Exit
17. View Visitor Log
18. Exit
Enter your choice (1-18):
Try these steps:
- Add a Student: Choose option 1, enter details like "Rahul Sharma", "rahul@example.com", "9876543210", "123, MG Road, Delhi". Note the
student_id
. - Add a Room: Choose option 5, enter room number "101" and capacity "2". Note the
room_id
. - Assign a Room: Choose option 6, enter the
room_id
andstudent_id
. - Add a Fee: Choose option 9, enter the
student_id
and amount due (e.g., 5000.0). - Record Payment: Choose option 10, enter the
fee_id
and amount paid (e.g., 3000.0). - Log a Complaint: Choose option 12, enter the
student_id
and a description like "Leaky tap". - Record a Visitor: Choose option 15, enter the
student_id
and visitor name. - View Reports: Choose options 11, 14, and 17 to see pending fees, complaints, and visitor logs.
For example:
Enter your choice (1-18): 1
Enter student name: Rahul Sharma
Enter email: rahul@example.com
Enter phone number: 9876543210
Enter address: 123, MG Road, Delhi
Student 'Rahul Sharma' added successfully with ID: 123e4567-e89b-12d3-a456-426614174000. Welcome to the hostel!
Extending the System
Want to make this project even cooler? Here are some ideas:
- GUI Interface: Use
tkinter
orPyQt
to create a graphical interface with buttons and forms. - Web App: Convert this to a web app using
Flask
orDjango
for online access. - Email Notifications: Send email reminders for fee due dates using
smtplib
. - QR Code Check-In: Generate QR codes for students to check in/out using
qrcode
. - Inventory Management: Track hostel inventory like beds, mattresses, or fans.
- Analytics Dashboard: Add charts for fee collection trends or complaint resolution times.
Here’s a quick tkinter
example for adding a student:
import tkinter as tk
from tkinter import messagebox
def add_student_gui():
name = name_entry.get()
email = email_entry.get()
phone = phone_entry.get()
address = address_entry.get()
if name and email and phone and address:
add_student(name, email, phone, address)
messagebox.showinfo("Success", f"Student '{name}' added!")
else:
messagebox.showerror("Error", "Please fill all fields!")
root = tk.Tk()
root.title("Hostel Management System")
tk.Label(root, text="Name").pack()
name_entry = tk.Entry(root)
name_entry.pack()
tk.Label(root, text="Email").pack()
email_entry = tk.Entry(root)
email_entry.pack()
tk.Label(root, text="Phone").pack()
phone_entry = tk.Entry(root)
phone_entry.pack()
tk.Label(root, text="Address").pack()
address_entry = tk.Entry(root)
address_entry.pack()
tk.Button(root, text="Add Student", command=add_student_gui).pack()
root.mainloop()
Tips and Best Practices
- Error Handling: Validate inputs (e.g., numeric capacity, valid email format).
- Data Backup: Regularly back up
hostel.db
to avoid data loss. - Comments: Add comments to your code for clarity.
- Modularize: Keep functions small and reusable.
- Test Thoroughly: Test edge cases like assigning an occupied room or deleting a non-existent student.
Common Issues and Fixes
- Database Locked Error: Ensure only one instance of the program is running.
- Invalid ID: Use the exact IDs printed by the program.
- No Output: Check if
hostel.db
is in the correct folder. - Payment Errors: Ensure
amount_paid
doesn’t exceedamount_due
.
Why This Project Rocks
This project is awesome because:
- It’s practical: Hostels need systems like this.
- It’s scalable: Add a GUI, web app, or mobile app.
- It’s educational: Learn Python, SQLite, and database concepts.
- It’s impressive: Perfect for college projects or job interviews.
Final Thoughts
Phew, that was a long ride, dosto! We’ve built a Hostel Management System in Python that handles students, rooms, fees, complaints, and visitors. You’ve got the complete source code, explanations, and ideas to take it further. Run the code, manage your virtual hostel, and maybe add a GUI or web interface to make it even cooler. Happy coding, and if you add new features, do share, yaar!